How to save an image from a URL in PHP
In this tutorial, we are going to see how to save an image from a URL in PHP. Sometimes it is necessary to download an image from a particular URL and use it in the project. It is easy to access the page and use the right mouse button to save the image. But what if you wanted to do it programmatically? The reasons may vary. If you have defined hundreds of image URLs and want to save them on your server, or if you need to use this concept in projects. Then certainly not going to upload each of these files manually.
There are two different approaches to download an image from a URL:
- Using PHP.
- Using cURL.
How to save an image from a URL using PHP
The following code snippet allows you to copy an image from a URL and save it to a folder using PHP.
- file_get_contents() – This function reads the image from the URL and returns the contents as a string.
- file_put_contents() – This function is used to write data from an image to a file.
<?php $url = 'https://stackhowto.com/wp-content/uploads/2020/11/cropped-stackhowto.png'; $img = 'images/logo.png'; // Save image file_put_contents($img, file_get_contents($url)); ?>
[st_adsense]
How to save an image from a URL using cURL
You can use cURL to save an image from a URL using PHP. The following code snippet helps you copy an image file from a URL using cURL in PHP.
<?php $url = 'https://stackhowto.com/wp-content/uploads/2020/11/cropped-stackhowto.png'; $img = 'images/logo.png'; // Save image $ch = curl_init($url); $fp = fopen($img, 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp); ?>[st_adsense]