Skip to content

Instantly share code, notes, and snippets.

Created October 12, 2010 09:18
Show Gist options
  • Save anonymous/621909 to your computer and use it in GitHub Desktop.
Save anonymous/621909 to your computer and use it in GitHub Desktop.
<?php
//<meta http-equiv="refresh" content="1;">
$url='http://www.baidu.com';
$fileName='test.zip';
$fsave = @filesize($fileName) or $fsave=0;
getFile($url,$fsave,20240,$content,$fsize);
echo $content;
if($fsave>=$fsize)exit('done');
$fp = fopen($fileName,'a');
if (flock($fp,LOCK_EX)){
fputs($fp,$content);
flock($fp,LOCK_UN);
}
echo $fsave.'/'.$fsize;
/**
* 函数getFile
* url 文件连接
* start 从文件start字节开始下载
* size 下载数据长度
* content 返回数据内容
* fsize 下载文件大小
*
*/
function getFile($url,$start=0,$size=102400,&$content,&$fsize){
$urlInfo = parse_url($url);
//请求头信息
$header = "GET $url HTTP/1.0\r\n";
//$header .= "RANGE: bytes=1";
//$header .= "RANGE: bytes=$start-".($start+$size);
//echo "RANGE: bytes=$start-".($start+$size)."<Br/>";
//$header .= "Connection: Close\r\n\r\n";
$header .= "connection: keep-alive\r\n\r\n";
//连接
$fp = fsockopen ($urlInfo['host'],80, $errno, $errstr,30);
//检测是否成功
if(!$fp){
exit('file no exists');
}else{
fputs ($fp, $header);
}
//去除头信息
while (!feof($fp)){
$str=fgets ($fp,1024);
echo $str."<br/>";
if(preg_match('/Content-Length: /si', $str, $arr)) {
$arr = explode('/',$arr[1]);
$fsize1 = trim($arr[1]);
}
if(preg_match('/Content-Range: bytes(.*)/si', $str, $arr)) {
$fsize2 = $arr[1];
}
if($str=="\r\n")break;
}
$fsize=!empty($fsize1)?$fsize1:$fsize2;
//返回内容
fseek($fp,$start);
$content=@fread($fp,$size);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment