Saving an Image from URL in PHP
Last Updated :
31 Jul, 2021
Sometimes, need to download an image from a particular URL and use it into the project. It's easy to go to the page and use right click button and save the image. But what if you wanted to do it programmatically? The reasons may vary person to person, developer to developer. If set of hundreds of image URLs given and somehow want to save them into the machine, or need to use this concept into the projects. Then definitely not going to download each one of those files manually.
There are two different approaches to download image from url which are listed below:
- Using basic file handling.
- Using an HTTP library called cURL.
Both of these approaches come with their own set of merits and demerits.
Using Basic File Handling: This is the fundamental and easiest way to accomplish the task. Just like any other file, start with the creation of an empty file and open it in "write" mode. After that, fetch the content from source URL and paste it into this file. And it is as simple as it sounds.
From the script, you can figure out on your own about what it does.
- Declaring two variables named as $url and $img, representing the source URL and destination file respectively.
- Use file_put_contents() function to write a string to a file that takes two arguments. One is the file name (or path) and the other is the content for that file.
- Use file_get_contents() function to read a file into a string.
Example:
php
<?php
$url =
'https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6-1.png';
$img = 'logo.png';
// Function to write image into file
file_put_contents($img, file_get_contents($url));
echo "File downloaded!"
?>
File downloaded!
Note: It save the image to the server with given name logo.png.
Now the only problem with this method is that it requires allow_url_fopen configuration to be set, which is set to 1 by default. But sometimes, project requirements don't allow to have this option. This may be because of some preventive security measures or just a design principle. In such cases, there is another method to save image.
Using HTTP library, cURL: Strictly speaking, cURL is not just an HTTP library. It has got several other data transferring protocols as well. As our image is on an HTTP server, we will limit ourselves to this small section of this library.
cURL allows to make HTTP requests in PHP. Start by initializing an instance of it and setting up some of the necessary options for the request, including the URL itself. Then execute this query which returns the content of the file. After that, the rest of the procedure is the same. As soon as we get the data, put it into a file and save it.
Approach:
- In this script, we defined a function file_get_contents_curl to replicate the behaviour of file_get_contents from the previously mentioned technique.
- Inside this function, we have initialised an instance of cURL using curl_init function in order to use it for fetching the data.
- After that, some options need to be set using curl_setopt so that this particular example can work. This function takes three arguments
- An instance of cURL
- The corresponding option that need to be set
- And the value to which option is set
In this example, the following options are set: - CURLOPT_HEADER, which is to ensure whether you need to receive the headers or not;
- CURLOPT_RETURNTRANSFER which transfers data as the return value of curl_exec function rather than outputting it directly.
- There is this another option CURLOPT_URL that sets the URL for the request.
- After that, we fetch the data from curl_exec and return it from the parent function.
- This data is then written on to the file on your machine using file_put_contents.
Example:
php
<?php
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$data = file_get_contents_curl(
'https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6-1.png');
$fp = 'logo-1.png';
file_put_contents( $fp, $data );
echo "File downloaded!"
?>
Output:
File downloaded!
This method provides a bit of flexibility while fetching the content from the internet. As mentioned earlier, it is not just limited to HTTP but can be used in many other circumstances as well. It allows to configure the transfer in whatever way you want. For example,
file_get_contents uses a simple GET request to fetch the data, but with cURL, can use GET, POST, PUT and other methods as well.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Similar Reads
How to get parameters from a URL string in PHP?
The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions.Note: The page URL and the parameters are separated by the ? character.parse_url() FunctionThe parse_url() function is used to return the components of a URL by parsing it. It parses a URL and return
2 min read
How to Resize JPEG Image in PHP ?
Why do we need to resize images? In a website, often, we need to scale an image to fit a particular section. Sometimes, it becomes necessary to scale down any image of random size to fit a cover photo section or profile picture section. Also, we need to show a thumbnail of a bigger image. In those c
2 min read
How to send a GET request from PHP?
There are mainly two methods to send information to the web server which are listed below: GET Method: Requests data from a specified resource. POST Method: Submits data to be processed to a specified resource. Get Method: The GET method sends the encoded user information appended to the page reques
2 min read
Dynamically generating a QR code using PHP
There are a number of open source libraries available online which can be used to generate a Quick Response(QR) Code. A good open source library for QR code generation in PHP is available in sourceforge. It just needs to be downloaded and copied in the project folder. This includes a module named "p
3 min read
How to extract img src and alt from html using PHP?
Extraction of image attributes like 'src', 'alt', 'height', 'width' etc from a HTML page using PHP. This task can be done using the following steps. Loading HTML content in a variable(DOM variable). Selecting each image in that document. Selecting attribute and save it's content to a variable. Outpu
2 min read
How to Upload Image into Database and Display it using PHP ?
Uploading the image/videos into the database and displaying it using PHP is the way of uploading the image into the database and fetching it from the database. Using the PHP code, the user uploads the image or videos they are safely getting entry into the database and the images should be saved into
8 min read
How to delete a file using PHP ?
To delete a file by using PHP is very easy. Deleting a file means completely erase a file from a directory so that the file is no longer exist. PHP has an unlink() function that allows to delete a file. The PHP unlink() function takes two parameters $filename and $context. Syntax: unlink( $filename,
2 min read
Web Scraping in PHP Using Simple HTML DOM Parser
Web Scraping is a technique used to extract large amounts of data from websites extracted and saved them to a local file in your computer or to a database or can be used as API. Data displayed by most websites can be viewed by using a web browser only. They do not offer the functionality to save a c
2 min read
How to check if URL contain certain string using PHP?
Given a URL and the task is to check the URL contains certain string or not. The URL are basically the strings. So in order to check the existence of certain strings, two approaches can be followed. The first approach is used to find the sub string matching in a string and second approach is to find
4 min read
How to make PDF file downloadable in HTML link using PHP ?
In web development, it is common to provide users with downloadable resources, such as PDF files. If you want to create a downloadable PDF link using HTML and PHP, this article will guide you through the process of making a PDF file downloadable when the user clicks on a link. ApproachCreate an HTML
3 min read