Saving image from URL is very useful when you want to copy an image dynamically from the remote server and store in the local server.
The file_get_contents() and file_put_contents() provides an easiest way to save remote image to local server using PHP. The image file can be saved straight to directory from the URL. In the example code snippet, we will provide two ways to save image from URL using PHP.
Save Image from URL using PHP
The following code snippet helps you to copy an image file from remote URL and save in a folder using PHP.
- file_get_contents() – This function is used to read the image file from URL and return the content as a string.
- file_put_contents() – This function is used to write remote image data to a file.
// Remote image URL $url = 'http://www.example.com/remote-image.png'; // Image path $img = 'images/tcmhack.png'; // Save image file_put_contents($img, file_get_contents($url));
Save Image from URL using cURL
You can use cURL to save an image from URL using PHP. The following code snippet helps you to copy an image file from URL using cURL in PHP.
// Remote image URL $url = 'http://www.example.com/remote-image.png'; // Image path $img = 'images/tcmhack.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);
That’s it, Your file must be saved to that desired location.
If you’re still facing difficulities in saving the files, feel free to post a comment. We will try our best to solve the issue.