php从URL下载文件的几种方法

时间:2017-07-28
本文章向大家介绍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);

注意:如果目标文件已存在,则将覆盖该文件