1. 程式人生 > 其它 >PHP 下載檔案&獲取檔案內容

PHP 下載檔案&獲取檔案內容

/**
     * 檔案下載到本地目錄
     * @param $url
     * @return string
     */
    function _download($url) {
        $folder = $this->path;
        set_time_limit(24 * 60 * 60); // 設定超時時間
        $destination_folder = $folder . '\\'; // 檔案下載儲存目錄,預設為當前檔案目錄
        if(!is_dir($destination_folder)) { // 判斷目錄是否存在
            $this
->_mkdirs($destination_folder); // 如果沒有就建立目錄 } $newfname = $destination_folder . basename($url); // 取得檔案的名稱\ $file = fopen($url, "rb"); // 遠端下載檔案,二進位制模式 if($file) { // 如果下載成功 $newf = fopen($newfname, "wb"); // 遠在檔案檔案 if($newf) // 如果檔案儲存成功 while
(!feof($file)) { // 判斷附件寫入是否完整 fwrite($newf, fread($file, 1024 * 8), 1024 * 8); // 沒有寫完就繼續 } } if($file) { fclose($file); // 關閉遠端檔案 } if($newf) { fclose($newf); // 關閉本地檔案 } return $newfname; }
function _mkdirs($path, $mode = "0755") { if(!is_dir($path)) { // 判斷目錄是否存在 $this->_mkdirs(dirname($path), $mode); // 迴圈建立目錄 mkdir($path, $mode); // 建立目錄 } return true; } /** * 獲取遠端檔案內容 * @param $url */ function _fopenUrl($url) { $file_content = ''; if(function_exists('file_get_contents')) { $file_content = @file_get_contents($url); } elseif(ini_get('allow_url_fopen') && ($file = @fopen($url, 'rb'))) { $i = 0; while(!feof($file) && $i++ < 1000) { $file_content .= strtolower(fread($file, 4096)); } fclose($file); } elseif(function_exists('curl_init')) { $curl_handle = curl_init(); curl_setopt($curl_handle, CURLOPT_URL, $url); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_handle, CURLOPT_FAILONERROR, 1); curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Trackback Spam Check'); //引用垃圾郵件檢查 $file_content = curl_exec($curl_handle); curl_close($curl_handle); } else { $file_content = ''; } return $file_content; }