To download a file from a URL using cURL in PHP, you can use the CURLOPT_RETURNTRANSFER and CURLOPT_BINARYTRANSFER options to get the file contents as a string, and then save the string to a file using file handling functions.
Here's an example:
$url = "https://www.example.com/image.jpg";
$filename = "image.jpg";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
if(curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
$fp = fopen($filename, "wb");
fwrite($fp, $response);
fclose($fp);
In this example, we specify the URL of the file to download and the filename to save the file as. We set the CURLOPT_RETURNTRANSFER , CURLOPT_BINARYTRANSFER , and CURLOPT_FOLLOWLOCATION options as before.
After executing the cURL session, we save the response as a file using file handling functions. We open a file handle using fopen (), write the contents of the response using fwrite (), and close the file handle using fclose ().
Note that if the file is very large, it may be better to use the CURLOPT_FILE option to write the response directly to a file without loading it into memory. Here's an example:
$url = "https://www.example.com/bigfile.zip";
$filename = "bigfile.zip";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_FILE, fopen($filename, 'w'));
curl_exec($ch);
if(curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
In this example, we use the CURLOPT_FILE option to open a file handle with the fopen () function and write the response directly to the file without loading it into memory.