user622378
user622378

Reputation: 2336

Download a image from SSL using curl?

How do I download a image from curl (https site)?

File is saved on my computer but why is it blank (0KB)?

function save_image($img,$fullpath){
    $ch = curl_init ($img);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0); 
    $rawdata=curl_exec($ch);
    curl_close ($ch);

    $fp = fopen($fullpath,'w');
    fwrite($fp, $rawdata);
    fclose($fp);
}

save_image("https://domain.com/file.jpg","image.jpg");

Upvotes: 6

Views: 10162

Answers (2)

AdamJonR
AdamJonR

Reputation: 4713

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);

should actually be:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

so curl knows that it should return the data and not echo it out.

Additionally, sometimes you have to do some more work to get SSL certs accepted by curl:
Using cURL in PHP to access HTTPS (SSL/TLS) protected sites

EDIT:

Given your usage, you should also set CURLOPT_HEADER to false as Alix Axel recommended.

In terms of SSL, I hope you'll take time to read the link I suggested, as there are a few different ways to handle SSL, and the fix Alix recommended may be OK if the data isn't sensitive, but does negate the security, as it forces CURL to accept ANY SERVER CERTS.

Upvotes: 6

Alix Axel
Alix Axel

Reputation: 154513

You need to add these options:

curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

Also, set CURLOPT_HEADER to false and CURLOPT_RETURNTRANSFER to true.

Upvotes: 4

Related Questions