Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download File to server from URL

Well, this one seems quite simple, and it is. All you have to do to download a file to your server is:

file_put_contents("Tmpfile.zip", file_get_contents("http://someurl/file.zip")); 

Only there is one problem. What if you have a large file, like 100mb. Then, you will run out of memory, and not be able to download the file.

What I want is a way to write the file to the disk as I am downloading it. That way, I can download bigger files, without running into memory problems.

like image 997
xaav Avatar asked Oct 15 '10 00:10

xaav


People also ask

How do I download files directly to a server?

If you're on Windows, download "Putty", and create a new connection to your server. Once your're connected to the server, type wget http://www.anywebsite.com/files/myvideo.avi and the video at this URL will be download in your current directory.

Can you download a PHP file from a website?

If the server is configured correctly, you cannot download a PHP file. It will be executed when called via the webserver. The only way to see what it does is to gain access to the server via SSH or FTP or some other method.


1 Answers

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

From the manual:

If data [that is the second argument] is a stream resource, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().

(Thanks Hakre.)

like image 129
alex Avatar answered Sep 22 '22 19:09

alex