php從URL下載文件的幾種方法


第一種方法:file_put_contents()

從PHP 5.1.0開始,file_put_contents()支持通過傳遞stream-handle作為$data參數逐個編寫:

set_time_limit(0); $file = file_get_contents('path of your file'); file_put_contents('file.ext', $file);

 

第二種方法:fopen 和fwrite

private function downloadFile($url, $path) { $newfname = $path; $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); } }

 

第三種方法:curl

function downloadUrlToFile($url, $outFileName) { if(is_file($url)) { copy($url, $outFileName); } else { $options = array( CURLOPT_FILE => fopen($outFileName, 'w'), CURLOPT_TIMEOUT => 28800, // set this to 8 hours so we dont timeout on big files CURLOPT_URL => $url ); $ch = curl_init(); curl_setopt_array($ch, $options); curl_exec($ch); curl_close($ch); } }

 

第四種方法:copy()

在php中使用一個簡單的方法 copy()

copy($source_url, $local_path_with_file_name);

注意:如果目標文件已存在,則將覆蓋該文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM