How to download and save an image from a URL using cURL in PHP?

To download and save an image from a URL using cURL in PHP, you can use the following steps:

  1. Initialize a new cURL session using the curl_init() function.
  2. Set the URL of the image to be downloaded using the curl_setopt() function with the CURLOPT_URL option.
  3. Set the option CURLOPT_RETURNTRANSFER to true using the curl_setopt() function. This will return the response as a string instead of outputting it directly.
  4. Execute the cURL session using the curl_exec() function and store the response in a variable.
  5. Check for any cURL errors using the curl_error() function. If an error occurs, handle it accordingly.
  6. Get the file name and extension from the URL using the basename() function.
  7. Open a file handle in write mode using fopen() with the desired file name.
  8. Write the response data to the file using the fwrite() function.
  9. Close the file handle using the fclose() function.
  10. Cleanup the cURL session using the curl_close() function.

Here's a sample code snippet that demonstrates these steps:

// URL of the image $imageUrl = 'https://example.com/image.jpg'; // Initialize cURL session $ch = curl_init($imageUrl); // Set cURL options curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute cURL session $response = curl_exec($ch); // Check for cURL errors if(curl_error($ch)) { echo 'cURL Error: ' . curl_error($ch); // Handle error here } // Get file name from URL $fileName = basename($imageUrl); // Open file handle $fileHandle = fopen($fileName, 'w'); // Write response data to file fwrite($fileHandle, $response); // Close file handle fclose($fileHandle); // Cleanup cURL session curl_close($ch); echo 'Image downloaded and saved successfully.';

Make sure that your PHP server has the cURL extension installed and enabled.