PHP CURL Download File

im trying to download a file from a url,
when I use the browser the download dialog works but when I use this code the new file on my server stay empty.

$ch = curl_init();
$source = "https://myapps.gia.edu/ReportCheckPortal/downloadReport.do?reportNo=$row['certNo']&weight=$row['carat']";
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$destination = "./files/certs/$row['certNo'].pdf";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);

example of url: https://myapps.gia.edu/ReportCheckPortal/downloadReport.do?reportNo=1152872617&weight=1.35

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I solved this problem using this:

curl_setopt($ch, CURLOPT_SSLVERSION,3);

This is the final code:

$source = "https://myapps.gia.edu/ReportCheckPortal/downloadReport.do?reportNo=1152872617&weight=1.35";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$data = curl_exec ($ch);
$error = curl_error($ch); 
curl_close ($ch);

$destination = "./files/test.pdf";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);

Solution 2

Your url using https connection. Use the following curl option as well.

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);

Solution 3

  1. Did you check if result actually contains data?
  2. with fputs on larger files you need to specify byte length
  3. Try using file_put_contents($destination, $data);

Solution 4

See if you can use the following code to help you.

//Create a cURL handle.
$ch = curl_init($fileUrl);

//Pass our file handle to cURL.
curl_setopt($ch, CURLOPT_FILE, $fp);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply