PHP cURL Part 2 (Downloading Files From URL)
04/04/2019 . 1 minute, 45 seconds to read . Posted by Admin#php #curl #phpcurl #learnphp #phpframework #phpcrud #crud #phptutorial #phpforms #phpfunctions
In our previous part of this article, we've learned about the basics of PHP cURL and getting contents of any URL using it. In this part, we'll use PHP cURL to download files from a URL.
<?php
$target_filename = "downloaded-image.png";
$target_url = "https://res.cloudinary.com/coderanks/image/upload/v1554377365/coderanks/articles/cookie.jpg";
//File downloading
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $target_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_AUTOREFERER, false);
curl_setopt($curl, CURLOPT_REFERER, "https://www.coderanks.com");
$result = curl_exec($curl);
curl_close($curl);
//Saving File
$file = fopen($target_filename, 'w');
fwrite($file, $result);
fclose($file);
?>
Description
As we discussed in the last part, curl_setopt() is used to set different options for the curl object. Let's check each option we set to download the file.
CUROPT_URL
Used to set the URL of the file from where the file will be downloaded.
CURLOPT_RETURNTRANSFER
Used to return output(By default curl displays out automatically).
CURLOPT_SSL_VERIFYPEER
Used to enable or disable SSL verification, we disabled SSL verifier to test this script on localhost.
CURLOPT_REFERER
Used to specify referrer from where the request is being generated. Normally, websites check from where the users are coming on their page for statistical or promotional purposes. So for curl, we should define a referral as the site, we're requesting.
CURLOPT_AUTOREFERER
Used to disable auto referral, this is useful when we need to pass a specific referral as discussed above.
Saving File
After curl executed successfully, we'll get file details in $result. Now we can save this in any file. Following code will open a file if exist, if not create it, write data and close file.
//Saving File
$file = fopen($target_filename, 'w');
fwrite($file, $result);
fclose($file);
This is all for this article scope, now you should be able to download any file from URL to local using PHP cURL. In the next part of this article, we'll check if a URL exists or not using PHP cURL.
Thanks for reading.