Craig Fitches
Craig Fitches

Reputation: 51

Download Image URL - PHP

I'm trying to create a script to download images to a local server and I'm having some issues with the images downloading. I have tested the following script on a standard image (http://www.urmob.co.uk/i/l/2860.jpg) and its working fine, however, when trying to download an image from the following location

https://s3-eu-west-1.amazonaws.com/mobile-phones-direct/phone/portraitimage/full/52122ad8-c918-450d-be10-5921c0a870cb.png

It has no file contents and therefore the image doesn't work. I believe it has something to do with the HTTPS? I originally tried the standard file_get_contents but that didn't work, now I'm trying a CURL version and it is still not working. The function I'm using looks like the below:

function grab_image($url,$saveto){
    $ch = curl_init ($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $raw=curl_exec($ch);
    curl_close ($ch);
    if(file_exists($saveto)){
        unlink($saveto);
    }
    $fp = fopen($saveto,'x');
    fwrite($fp, $raw);
    fclose($fp);
}

Does anyone know why this isn't working?

Thanks,

Craig

Upvotes: 2

Views: 932

Answers (2)

Rakesh Sharma
Rakesh Sharma

Reputation: 13738

you are getting image from ssl url trying to remove https and use http

or try by adding :-

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

Upvotes: 0

Latheesan
Latheesan

Reputation: 24116

This is very simple:

test.php

<?php

// image source
$image_url = 'https://s3-eu-west-1.amazonaws.com/mobile-phones-direct/phone/portraitimage/full/52122ad8-c918-450d-be10-5921c0a870cb.png';

// download image
file_put_contents('downloaded_image.jpg', file_get_contents($image_url));

// display
echo '<img src="downloaded_image.jpg" >';

It works for me:

enter image description here


If you want to keep using the curl version and fix that ssl error, add this to your code:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

Upvotes: 2

Related Questions