Skip to content


Download a Remote File Using PHP

On hosts with safe_mode turned on, it can be difficult to get remote files with a system call to wget or curl. Here is a PHP function that will get a file with an HTTP GET. I use it to download remote images. It returns the binary data in a variable that can be written to a file.

<?php
function http_get_file($url)    {

   $url_stuff = parse_url($url);
   $port = isset($url_stuff['port']) ? $url_stuff['port']:80;

   $fp = fsockopen($url_stuff['host'], $port);

   $query  = 'GET ' . $url_stuff['path'] . " HTTP/1.0\n";
   $query .= 'Host: ' . $url_stuff['host'];
   $query .= "\n\n";

   fwrite($fp, $query);

   while ($line = fread($fp, 1024)) {
       $buffer .= $line;
   }

   preg_match('/Content-Length: ([0-9]+)/', $buffer, $parts);
   return substr($buffer, - $parts[1]);
}
?>

Original function found on php.net

Popularity: 39% [?]

Posted in PHP, Snippets.


8 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Bala Krishna says

    What about 2GB file download. I don’t think $buffer variable is able to handle this much of binary data and then save later on disk.. do you have any idea about this.. please share..

  2. sooraj says

    How to read excel data with php ?

  3. Mike Robinson says

    Why not just do file_get_contents() ?

  4. iallien says

    how can i downlaod file using PHP??

    wat is the code/script for it??

    please help me..

  5. SIFE says

    Salamo Alikom
    @iallien
    use curl ,it is more easy since the knowledge of HTTP protocol is optional .

    • damonp says

      Yes cURL would be easier, but the caveat in the first sentence of the post is that this is a workaround when cURL is not available on the host or other security features prevent other methods of downloading a remote file.

      Back in 2005 when this was written, cURL was not as standard as it is now.

Continuing the Discussion

  1. How to download a remote file in php and then save it | HumanUmbrella.com linked to this post on 12/8/2007

    [...] it from -> this site [...]

  2. OnicSoft Designs » Using php to download a remote file. linked to this post on 1/31/2009

    [...] was googling for a better way of doing this I came up with this method and have to figure out how to add it tot he mix, basically they said it would be able to use it [...]



Some HTML is OK

or, reply to this post via trackback.