Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download a image from SSL using curl?

Tags:

php

curl

ssl

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");
like image 442
user622378 Avatar asked Feb 18 '11 18:02

user622378


People also ask

How do I download files using curl?

How to download a file with curl command. The basic syntax: Grab file with curl run: $ curl https://your-domain/file.pdf. Get file using ftp or sftp protocol: $ curl ftp://ftp-your-domain-name/file.tar.gz.

How do I download a tar file with curl?

To download you just need to use the basic curl command but add your username and password like this curl --user username:password -o filename. tar. gz ftp://domain.com/directory/filename.tar.gz . To upload you need to use both the –user option and the -T option as follows.

How do I download files using curl Windows?

To download a file with Curl, use the --output or -o command-line option. This option allows you to save the downloaded file to a local drive under the specified name. If you want the uploaded file to be saved under the same name as in the URL, use the --remote-name or -O command line option.

Can curl work with https?

What is Curl? Curl is a command line tool for transferring data to and from servers. Curl supports over 25+ protocols including HTTP and HTTPS.


1 Answers

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.

like image 67
AdamJonR Avatar answered Sep 21 '22 00:09

AdamJonR