Wednesday, April 20, 2011

Best way to download a file in PHP

Which would be the best way to download a file from another domain in PHP? i.e. A zip file.

From stackoverflow
  • cURL

    here is an example.

  • The easiest one is file_get_contents(), a more advanced way would be with cURL for example. You can store the data to your harddrive with file_put_contents().

    John T : gotta be careful with file_get_contents() though. All of that data is held in a string. PHP's default memory limit is usually fairly low (16M IIRC), so if he's on shared hosting and the said files he's downloading are fairly large... he's gonna have a hard time with that.
    John T : unless you have a nice shared host and he will bump the memory for you on PHP, or you have your own server. Even then it's still kind of an iffy idea.
    jerebear : Also, file_get_contents is disabled on more secure boxes to avoid hacker attempts when trying to access files on other domains.
  • normally, the fopen functions work for remote files too, so you could do the following to circumvent the memory limit (but it's slower than file_get_contents)

    <?php
    $handle = fopen("http://www.example.com/", "rb");
    $fp = fopen($localfile, 'w');
    $contents = '';
    while (!feof($handle)) {
      $content = fread($handle, 8192);
      fwrite($fp, $content);
    }
    fclose($handle);
    fclose($fp);
    ?>
    

    copied from here: http://www.php.net/fread

0 comments:

Post a Comment