Php save image to folder from web

I’m looking to be able to get images from a remote url and save them to a folder on my site…

I see lots of examples of file upload, but not where the file is from a remote url.

Any clues would be very helpful!

From the manual

$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        echo $buffer;

If your PHP is able to open remote files, then you can replace /tmp/inputfile.txt with the remote URL.

You can use CURL, with the CURLOPT_BINARYTRANSFER and CURLOPT_RETURNTRANSFER options. Additionally, if the file type of the image varies, you might also wanna use curl_getinfo function with CURLINFO_CONTENT_TYPE option to get the file type.


so i have tried to save the image to the folder…i get a file saved, but it doesnt read back when viewed on the browser…taking it the image file hasnt been created correctly?

$handle = @fopen($img, "r");
if ($handle) {
   while (!feof($handle)) {
       $buffer = fgets($handle, 4096);
       //echo $buffer;

   $filename = "images/".$id.".jpg";
   $mystring = fopen($filename, "wb");
   $handle = fopen($filename, "wb");
   $numbytes = fwrite($handle, $buffer);

Since you aren’t echoing it, but storing it in the buffer, than it from $buffer = fgets to $buffer .= fgets. this way, it will append to $buffer each time.

ah thx that sorted it :slight_smile:

Actually if i now want to check to see if the image size is what i need…if not resize to specific width/height…how would i do this?

I remember there is a php function to get filesize:

list($width, $height, $type, $attr) = getimagesize($img);

this will give me the width and height, so i can do conditional logic to see if i need to resize…

so to resize…how can i make this work with my stored $buffer (found this)?

$src = imagecreatefromjpeg($buffer);
$filename = "images/". $_FILES['uploadfile']['name'];

Damn! Just realised that this way to grab the image is fine when executing the script via the browser, but when done via cronjob, the remote server is blocking the connection (to stop hotlinking presumabley)

Think i may have to use curl instead…

I found this:

$image_url = "";
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $image_url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

// Getting binary data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

$image = curl_exec($ch);

// output to browser
header("Content-type: image/jpeg");
print $image;

How can i adapt this to save the file to my images folder?

Hei, here is the code to save it to a directory on your server, after fetching image:
$f = fopen(‘/home/www/path/image.jpg’, ‘w’);
fwrite($f, $image);