有沒有考慮過用PHP來做多線程操作~
最近完善下載類中一個遠程下載檔案 考慮是不是可以分別分段讀取檔案內容 最後組合。經測試可行哦~ 這是我測試的本地檔案~
我想的是咋個可以最簡單封裝針對任意本地檔案 or遠程檔案 進行操作! 請看:
//PHP分段讀取檔案 這裡我只分了兩段 實際上可以通過檔案大小 按照預定段大小 進行分段..
$file = dirname(__FILE__).'/bullyframework_zend.7z';
echo filesize($file);
$handle = fopen($file, "rb");
$contents = fread($handle, ceil(filesize($file)/2));//分兩次讀取檔案組合
$now_tell = ftell($handle);//擷取當前指標
$end = fread($handle, filesize($file) - $now_tell);//從當前指標處讀取剩餘檔案
fclose($handle);
file_put_contents('test.7z', $contents.$end);//寫入檔案 驗證檔案是否完整
echo "
";
echo filesize('test.7z');
?>
------解決方案--------------------
分塊下載需要雙方都支援“斷點續傳”
一般下載工具都支援,所以你需要做的是伺服器端。php實現的斷點續傳服務大致如下
PHP code
// Begin writing headers header("Cache-Control:"); header("Cache-Control: public"); header("Content-Type: $ctype"); $filespaces = str_replace("_", " ", $filename); // if your filename contains underscores, replace them with spaces $header='Content-Disposition: attachment; filename='.$filespaces; header($header); header("Accept-Ranges: bytes"); $size = filesize($file); // check if http_range is sent by browser (or download manager) if(isset($_SERVER['HTTP_RANGE'])) { // if yes, download missing part $seek_range = substr($_SERVER['HTTP_RANGE'] , 6); $range = explode( '-', $seek_range); if($range[0] > 0) { $seek_start = intval($range[0]); } if($range[1] > 0) { $seek_end = intval($range[1]); } header("HTTP/1.1 206 Partial Content"); header("Content-Length: " . ($seek_end - $seek_start + 1)); header("Content-Range: bytes $seek_start-$seek_end/$size"); } else { header("Content-Range: bytes 0-$seek_end/$size"); header("Content-Length: $size"); } //open the file $fp = fopen("$file","rb"); //seek to start of missing part fseek($fp,$seek_start); //start buffered download $n = 0; while(!feof($fp)) { //reset time limit for big files echo fread($fp,1024*$speed); } fclose($fp); exit;