To save an image from a URL to a local file in PHP, you can use the file_put_contents
function in combination with the file_get_contents
function:
$url = 'https://example.com/image.jpg';
$image = file_get_contents($url);
file_put_contents('image.jpg', $image);
This code will download the image from the given URL and save it to a file named image.jpg
in the current directory.
Alternatively, you can use the curl
functions to download the image:
$url = 'https://example.com/image.jpg';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$image = curl_exec($ch);
curl_close($ch);
file_put_contents('image.jpg', $image);
Note that you may need to set additional curl options depending on the server configuration, such as CURLOPT_SSL_VERIFYPEER
and CURLOPT_FOLLOWLOCATION
.
You should also check the HTTP status code returned by the server to make sure the image was successfully downloaded. You can use the curl_getinfo
function to get the HTTP status code:
$url = 'https://example.com/image.jpg';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$image = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status == 200) {
file_put_contents('image.jpg', $image);
} else {
// Handle error
}