有沒有思忖過用PHP來做多線程操作

來源:互聯網
上載者:User
有沒有考慮過用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; 
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.