将文件从外部链接远程下载到我的服务器 - 下载过早停止 [英] Remotely download a file from an external link to my server - download stops prematurely
问题描述
我有一个页面集,其中我输入文件的URL,我让我的服务器下载该文件,并将其保存到我的服务器上的文件夹。问题是,我不知道如何下载文件到我的服务器。我尝试了以下两种方法,他们都没有工作。
I have a page set where I enter the url of an file and I have my server download that file and save it into a folder on my server. The issue is that I dont know how to download a file to my server. I have tried both of the following methods, and they both didn't work.
这一个抛出一个关于失败的开放流的错误:
This one throws an error about a failed open stream:
$url = 'http://www.example.com/file.zip';
$enc = urlencode($url);
$dir = "/downloads/file.zip";
$raw = file_get_contents($enc);
file_put_contents($dir, $raw);
这一个工作,但我只得到一个270kb文件中的18kb:(我试图增加超时)
This one works but I only get 18kb out of a 270kb file: ( I have tried to increase the timeout)
set_time_limit(0);
$url = 'http://www.eample.com/file.zip';
$fp = fopen ('/downloads/file.zip', 'w+');
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_BINARYTRANSFER => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FILE => $fp,
CURLOPT_TIMEOUT => 50,
CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
));
$results = curl_exec($ch);
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
推荐答案
This one throw a error about a failed open stream:
This one throws an error about a failed open stream:
...
$enc = urlencode($url);
...
,因为你不需要urlencode那个已经正确编码的url。尝试:
I'd say no wonder, because you don't need to "urlencode" that url which is already properly encoded. Try:
$url = 'http://www.example.com/file.zip';
$file = "/downloads/file.zip";
$src = fopen($url, 'r');
$dest = fopen($file, 'w');
echo stream_copy_to_stream($src, $dest) . " bytes copied.\n";
请参阅 stream_copy_to_stream
Docs 。如果您需要设置更多HTTP事件(如用户代理等),请使用 HTTP上下文选项 。
See stream_copy_to_stream
Docs. If you need to set more HTTP thingies like user-agent etc. use the HTTP Context OptionsDocs.
这篇关于将文件从外部链接远程下载到我的服务器 - 下载过早停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!