Copyright © Mike's Blog
Design by Dzignine
2011年12月28日 星期三

php小紀事

最近在做一個FTP下載的控管網頁
找到很多不錯的code 紀錄一下

透過php下載檔案大的作法 這邊把檔案做切割處理
然後在一塊一塊下載 而且還可以限制流量

//這個一定要設定,PHP頁面執行時間,不然載到一半就結束了
ini_set('max_execution_time', '0')

//定義切割大小

define('CHUNK_SIZE', 150*8); // Size (in bytes) of tiles chunk 512KB

// 讀取區塊

function readfile_chunked($filename, $retbytes = TRUE) {
    $buffer = '';
    $cnt =0;
    // $handle = fopen($filename, 'rb');
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
      return false;
    }
    while (!feof($handle)) {
      $buffer = fread($handle, CHUNK_SIZE);
      echo $buffer;
      ob_flush();
      flush();
      if ($retbytes) {
        $cnt += strlen($buffer);
      }
    }
    $status = fclose($handle);
    if ($retbytes && $status) {
      return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;
}

另一個是檔案瀏覽器 是open source的code
超級厲害 功能很完善 而且開發者還在維護中
有手機板 上傳管理 會員登入等功能 Encode Explorer

最後碰到一個問題就是 我想要顯示正確的檔案大小發現超過2G就會有問題
Encode Explorer有修正 可是只能在非windows上環境跑
後來我爬了一下code 只到許多解決辦法 最後挑出這個最好用的方法:

/**
* 這個方法是用curl的方式去讀取檔案大小
* 所以讀取網頁的話會有bug 可以再自行修正
*
*/
function ffilesize($file){
    $ch = curl_init($file);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    $data = curl_exec($ch);
    curl_close($ch);
    if ($data === false) 
      return false;
    if (preg_match('/Content-Length: (\d+)/', $data, $matches))
      return (float)$matches[1];
}

附上一個小記錄 是關於NetBeans使用class時對於function的註解
加上自行這段註解會在hint中顯示 其實還頗方便的

/**
*
* 這邊是function說明
* @param string $filepath 
* filepath說明
* @return string
* 說明
*
*/