Remotely download a file from an external link to my server - download stops prematurely

假如想象 提交于 2019-11-30 05:59:55

问题


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);

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);
 }

回答1:


This one throws an error about a failed open stream:

...
$enc = 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";

See stream_copy_to_stream­Docs. If you need to set more HTTP thingies like user-agent etc. use the HTTP Context Options­Docs.



来源:https://stackoverflow.com/questions/9730285/remotely-download-a-file-from-an-external-link-to-my-server-download-stops-pre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!