How to download a remote file in php and then save it

So, I found a site with all the lolcat images named cat1.jpg, cat2.jpg, cat3.jpg, etc. I wanted to know how many were there as I saw cat389.jpg. As it turns out, it’s only 390, so that’s all I need to know.

So, I decided to write a little PHP script to grab all the images. First, I set up a loop to do this, from 1-390. which is done like


Then, I get the data from the URL. By putting “.$i.” in the filename string, I can increment the filename as the loop increments. so it’ll get filename1.jpg, filename2.jpg, etc…

$x = http_get_file('http://the_site/filename'.$i.'.jpg');

This is a method call, which I’ll post next.

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.0n";
$query .= 'Host: ' . $url_stuff['host'];
$query .= "nn";
fwrite($fp, $query);
while ($line = fread($fp, 1024)) {
$buffer .= $line;
preg_match('/Content-Length: ([0-9]+)/', $buffer, $parts);
return substr($buffer, - $parts[1]);

Got it from -> this site (Thanks!)

Finally, you write what you get back from this method ( a buffer of data ) to a file, which in PHP is done like this: (again, “cat”.$i.”.jpg” creates cat1.jpg,cat2.jpg for whatever i is at the time.)

$File = "cat".$i.".jpg";
$Handle = fopen($File, 'w');
$Data = $x;
fwrite($Handle, $Data);
print "Data Written";

All you have to do is make sure that the directory your script is in has the ability to create/write files.

That’s it!


edit: My style scripting messes with the quotes in the script, so I’ve attached it as a standalone file to correct for this.

Here’s the code all together:
How to download a remote file in php and then save it

Rename the file to remote-file-download.php after you download it.


Tagged with: , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.