How to download a file from a URL using cURL in PHP?

To download a file from a URL using cURL in PHP, you can use the following code:

<?php // URL of the file to download $url = "https://example.com/file.jpg"; // Destination path to save the downloaded file $destination = "path/to/save/file.jpg"; // Initialize cURL session $curl = curl_init(); // Set the URL to download curl_setopt($curl, CURLOPT_URL, $url); // Return the transfer as a string instead of outputting it directly curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Execute the cURL session $data = curl_exec($curl); // Check if an error occurred during the download if ($data === false) { echo "cURL Error: " . curl_error($curl); } else { // Save the downloaded file to the destination path file_put_contents($destination, $data); echo "File downloaded successfully."; } // Close cURL session curl_close($curl); ?>

In this example, you need to specify the URL of the file you want to download using the $url variable. The downloaded file will be saved to the specified destination path using the $destination variable.

The cURL options CURLOPT_URL is set to the URL, and CURLOPT_RETURNTRANSFER is set to true to return the downloaded file as a string.

After executing the cURL session with curl_exec, you can check if any error occurred during the download using curl_error. If the download was successful, you can save the downloaded file to the destination path using file_put_contents.

Finally, make sure to close the cURL session using curl_close.