使用PHP将远程文件下载到服务器 [英] Download Remote File to Server with PHP

查看:488
本文介绍了使用PHP将远程文件下载到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的两天中,我一直在寻找所有的地方,尝试所有的事情,仍然无法获得任何工作。我觉得这应该是一件比较简单的事情。



我想做的是将远程文件从URL下载到我的服务器上的目录。 p>

所以,例如,如果

  $ _ url = http:// www.freewarelovers.com/android/download/temp/1306495040_Number_Blink_1.1.1.apk 

$ _ dir = / www / downloads /



然后当所有的说完,我想要$ code> 1306495040_Number_Blink_1。 1.1.apk 在 / www / downloads /



code> copy()函数,我试过

  file_put_contents($ _ dir 。$ _ file_name,file_get_contents($ _ url)); 

并得到以下错误:



file_get_contents():无法打开流:HTTP请求失败!

解决方案

应该这样做:

  set_time_limit(0); 

$ url ='http://www.freewarelovers.com/android/download/temp/1306495040_Number_Blink_1.1.1.apk';
$ file = fopen(dirname(__ FILE__)。'/downloads/a.apk','w +');

$ curl = curl_init($ url);

//更新PHP 5.4数组()可以写成[]
curl_setopt_array($ curl,[
CURLOPT_URL => $ url,
// CURLOPT_BINARYTRANSFER => 1,---没有PHP 5.1.3的影响
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FILE => $ file,
CURLOPT_TIMEOUT => 50,
CURLOPT_USERAGENT =>'Mozilla / 4.0(兼容; MSIE 5.01; Windows NT 5.0)'
]);

$ response = curl_exec($ curl);

if($ response === false){
//更新为PHP 5.3使用Namespaces异常()成为\Exception()
throw new \Exception ('Curl error:'。curl_error($ curl));
}

$ response; //做某事与回应。


I've been looking all over the place for the last two days and trying everything and still can't get anything to work. I feel like this should be a relatively simple thing to do.

All I want to do is download a remote file from a URL to a directory on my server.

So, for example, if

$_url = http://www.freewarelovers.com/android/download/temp/1306495040_Number_Blink_1.1.1.apk

and $_dir = /www/downloads/

Then when all is said and done I want 1306495040_Number_Blink_1.1.1.apk in /www/downloads/

I've tried the copy() function, I've tried

file_put_contents("$_dir.$_file_name", file_get_contents($_url));

and get the following error:

file_get_contents(): failed to open stream: HTTP request failed!

解决方案

This should do it :

set_time_limit(0);

$url = 'http://www.freewarelovers.com/android/download/temp/1306495040_Number_Blink_1.1.1.apk';
$file = fopen(dirname(__FILE__) . '/downloads/a.apk', 'w+');

$curl = curl_init($url);

// Update as of PHP 5.4 array() can be written []
curl_setopt_array($curl, [
    CURLOPT_URL            => $url,
//  CURLOPT_BINARYTRANSFER => 1, --- No effect from PHP 5.1.3
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_FILE           => $file,
    CURLOPT_TIMEOUT        => 50,
    CURLOPT_USERAGENT      => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
]);

$response = curl_exec($curl);

if($response === false) {
    // Update as of PHP 5.3 use of Namespaces Exception() becomes \Exception()
    throw new \Exception('Curl error: ' . curl_error($curl));
}

$response; // Do something with the response.

这篇关于使用PHP将远程文件下载到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆