tags:

views:

49

answers:

3

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.

+1  A: 

Look at fopen().

Unfortunately, for writing piece by piece, you can't use the more abstract file_put_contents().

alex
That wouldn't be my first choice. If `allow_fopen_url Off` is set in php.ini (good idea for security), your script would be broken.
idealmachine
@idealmachine I think `file_get_contents()` would not work either if that were the case (see OP).
alex
Ok, not really a lot of help with the code, but yes, this will work. Try to be more specific next time, please. See my answer for specific code.
geoff
@geoff I was specific, I mentioned the function you wanted. What you may have wanted was someone to write the code for you - but I'm sure you learned something doing it yourself. Also, if we are going to comment on each other's SO interactions - [please accept some more answers](http://blog.stackoverflow.com/2009/08/new-question-asker-features/) :)
alex
+2  A: 

Try using cURL

set_time_limit(0); // unlimited max execution time
$options = array(
  CURLOPT_FILE => '/path/to/download/the/file/to.zip',
  CURLOPT_TIMEOUT => 28800, // set this to 8 hours so we dont timeout on big files
  CURLOPT_URL => 'http://remoteserver.com/path/to/big/file.zip',
);

$ch = curl_init();
curl_setopt_array($ch, $options);
curl_exec($ch);

Im not sure but i beleive witht he file option it writes as it pulls the data... ie. not buffered.

prodigitalson
Normally, this would be fine, but I have this code in a web app, so I cant be sure users will have cURL installed. However, I did give this a vote up.
geoff
@geoff: fair point.
prodigitalson
@Geoff is it a distributed web app? Because if you control the hosting, then it doesn't matter about your users (cURL is a library on your server).
alex
No. I do not control hosting. It is a distributed web app that anyone could have.
geoff
A: 
private function downloadFile ($url, $path) {

  $newfname = $path;
  $file = fopen ($url, "rb");
  if ($file) {
    $newf = fopen ($newfname, "wb");

    if ($newf)
    while(!feof($file)) {
      fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
    }
  }

  if ($file) {
    fclose($file);
  }

  if ($newf) {
    fclose($newf);
  }
 }
geoff