CartMetrix - Do you know yours?

« Delete Files Newer Than | Home | Lighttpd Startup Script »

9/29/2005

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: 41%

Trackback:

Related Posts

3 Responses to “Download a Remote File Using PHP”

  1. How to download a remote file in php and then save it | HumanUmbrella.com said:

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

  2. Bala Krishna said:

    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..

  3. sooraj said:

    How to read excel data with php ?

Post your opinion

Verification Image

Please type the letters you see in the picture.

Subscribe without commenting


damonparker.org is proudly powered by WordPress
Entries (RSS) and Comments (RSS).

copyright © 2002-2008 damonparker.org. all rights reserved.

Close
E-mail It