Save image from url with curl PHP
To save an image from a URL using PHP and cURL, you can use the following function:
To save an image from a URL using PHP and cURL, you can use the following function. This snippet requires the curl and gd PHP extensions.
Example: Save an image from a URL using PHP and cURL
<?php
function saveImage($image_url, $image_name)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $image_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($data === false || $http_code !== 200) {
return false;
}
$image = imagecreatefromstring($data);
if ($image === false) {
return false;
}
$image_name = preg_replace('/[^A-Za-z0-9\. -]/', '', $image_name);
imagejpeg($image, $image_name, 100);
imagedestroy($image);
return true;
}📺 Watch a video course: Learn object oriented PHP
To use this function, pass the URL of the image as the first argument and the desired name for the saved image as the second argument. For example:
Example: Save image to the current working directory
<?php
saveImage("http://example.com/image.jpg", "image.jpg");This will save the image to the current working directory with the specified name. You can also specify a different directory by including the path in the image name. For example:
Example: Save image to a different directory
<?php
saveImage("http://example.com/image.jpg", "/path/to/directory/image.jpg");Note: The example above uses
imagejpeg(), which forces JPEG output. For PNG or GIF images, replaceimagejpeg()withimagepng()orimagegif()to preserve transparency and animation.