Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need php script to download a file on a remote server and save locally

Tags:

php

download

Trying to download a file on a remote server and save it to a local subdirectory.

The following code seems to work for small files, < 1MB, but larger files just time out and don't even begin to download.

<?php

 $source = "http://someurl.com/afile.zip";
 $destination = "/asubfolder/afile.zip";

 $data = file_get_contents($source);
 $file = fopen($destination, "w+");
 fputs($file, $data);
 fclose($file);

?>

Any suggestions on how to download larger files without interruption?

like image 950
Ralph Canapa Avatar asked Dec 21 '10 21:12

Ralph Canapa


People also ask

How Force download file from remote server PHP?

Use the readfile() function with application/x-file-to-save Content-type header, to download a ZIP file from remote URL using PHP. header("Content-type: application/x-file-to-save"); header("Content-Disposition: attachment; filename=". basename($remoteURL));


3 Answers

$ch = curl_init();
$source = "http://someurl.com/afile.zip";
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);

$destination = "/asubfolder/afile.zip";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);
like image 184
Parris Varney Avatar answered Oct 05 '22 06:10

Parris Varney


file_get_contents shouldn't be used for big binary files because you can easily hit PHP's memory limit. I would exec() wget by telling it the URL and the desired output filename:

exec("wget $url -O $filename");
like image 33
Blagovest Buyukliev Avatar answered Oct 05 '22 04:10

Blagovest Buyukliev


Since PHP 5.1.0, file_put_contents() supports writing piece-by-piece by passing a stream-handle as the $data parameter:

file_put_contents("Tmpfile.zip", fopen("http://someurl/file.zip", 'r'));
like image 35
Kuldeep Avatar answered Oct 05 '22 05:10

Kuldeep