Download a Remote File Using PHP

by damonp on September 29, 2005

in PHP,Snippets

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

Update: 3-Feb-11
Updated function to download a remote file with PHP and cURL.

Popularity: 48%

Most Popular Posts

Damon Parker is a freelance sysadmin and web developer in Texas. He specializes in server setup, server security and high performance server configurations. Need help setting up a web server or getting a server back online after a crash or hack? Email Damon

{ 7 comments… read them below or add one }

Bala Krishna March 29, 2008 at 1:05 pm

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

Reply

nisha June 9, 2010 at 4:52 pm

Why dont u use FTP then. 2GB file is not for http small packets.
If I tell you solution for 2GB then you will ask tomorrow “what
about 25GB file I have on server” .. there is no end to your demands.

Reply

sooraj April 29, 2008 at 3:40 am

How to read excel data with php ?

Reply

Mike Robinson April 14, 2009 at 11:51 pm

Why not just do file_get_contents() ?

Reply

iallien August 22, 2009 at 7:37 am

how can i downlaod file using PHP??

wat is the code/script for it??

please help me..

Reply

SIFE September 29, 2009 at 7:14 am

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

Reply

damonp September 29, 2009 at 8:32 am

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.

Reply

Leave a Comment

{ 2 trackbacks }

Previous post:

Next post: