Downloading Images from a URL
Most of the time, we tried to get an image in the web by just right-clicking the image in the webpage then select “Save Image As…” in Firefox or “Save Picture As…” in Internet Explorer. This is the most common and easiest way to download the image.
Now, there comes a time that you will need to download the image using your PHP script dynamically then save it in our server. How is that possible? With the use of PHP’s file functions, fopen(), file_get_contents(), and fwrite() , we will be able to just do that. These two scripts i will be sharing will show us how to do that. But first, make sure you meet the following criteria:
- The server hosting the script should not be in a firewall;
- Make sure the fopen wrapper is enabled in your server. If you’re in a shared hosting account, you better ask your webhosting tech support for help; and
- Make sure the folder where you will be saving the downloaded images has a write permission (CHMOD 777 would do).
That’s it, and now we’re off to writing our scripts:
Script 1:
<?php
$x = file_get_contents("http://i.ytimg.com/vi/jhiPE0tiZkE/default.jpg", FILE_BINARY);
$handle = fopen("/tmp/default.jpg", "w");
fwrite($handle, $x);
fclose($handle);
?>
Script 2:
<?php
$imageurl = 'http://i.ytimg.com/vi/jhiPE0tiZkE/default.jpg';
$handle1 = @fopen($imageurl,'r');
$imagefile = basename($imageurl);
$handle2 = @fopen('/myupload/'.$imagefile,'w');
if ($handle1) {
while (!feof($handle1)) {
$imagecontent = fgets($handle1, 4096);
@fwrite($handle2,$imagecontent);
}
fclose($handle2);
fclose($handle1);
}
?>
Just be careful in using this scripts. Always remember that there are copyright issues in using these images.
Happy scripting.
NB. thanks to Sir Clod and Ryan for sharing us these scripts.
download, fget, file, fopen, fwrite, php, script, Scripts, urlRelated Posts:






March 9th, 2008 at 4:55 am
Neither of these are working for me. I copied them exactly as you have them after creating the tmp and myupload folders and setting the permissions to 777. The fopen wrapper in enabled on my server (I use 1and1). Any help is greatly appreciated!
March 10th, 2008 at 1:03 am
what is your exact error message? can you post it here? the scripts works perfectly fine as-is if all requirements are met.
thanks.
March 10th, 2008 at 1:04 am
or remove the error suppressor (@) to display the warnings/error messages.