in this tutorial we will discuss how to download image from the url in php
download image from URL is very useful when we need to copy an image dynamically from the remote server and store to our local server. The file_get_contents() and file_put_contents() fucntion give us a simpler way to download or save remote image to our local server in PHP. The image file can be saved directly to directory from the URL. In the sample code, we will provide two different ways to download or save image from URL in PHP.
download or Save Image from URL in PHP
The given code will helps you to copy/download an image file from URL and download/save in a folder in PHP.
file_get_contents() – is used to read the image file from URL and return the content as a string.
file_put_contents() – is used to write remote image record to a file.
// Remote image URL $url = 'http://www.example.com/remote-image.png'; // Image path $img = 'images/codexworld.png'; // Save image file_put_contents($img, file_get_contents($url));
download Image from URL using the cURL method
We can use cURL method to download/save an image from URL in PHP. The given code sample will helps us to copy an image file from URL using cURL method in PHP.
// Remote image URL $url = 'http://www.example.com/remote-image.png'; // Image path $img = 'images/codexworld.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);
Also read: How to Validate Password Strength using PHP