php该怎么下载文件,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);

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值