To download and save an image from a URL using cURL in PHP, you can use the following steps:
curl_init()
function.curl_setopt()
function with the CURLOPT_URL
option.CURLOPT_RETURNTRANSFER
to true
using the curl_setopt()
function. This will return the response as a string instead of outputting it directly.curl_exec()
function and store the response in a variable.curl_error()
function. If an error occurs, handle it accordingly.basename()
function.fopen()
with the desired file name.fwrite()
function.fclose()
function.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.