How to save an image from a URL in PHP
Today we’ll explain to you how to save an image from a URL in PHP. Sometimes we need to download images from a remote server and use them in projects. Therefore we will show you a few different ways to save an Image to the folder using PHP.
Two ways to save image from URL in PHP
1. Using basic file handling function
It is a very simple way to save an image from the URL using PHP functions file_get_contents() and file_put_contents().
- file_get_contents(): This function is used to read file from URL and return as a string.
- file_put_contents(): This function is used to write a string to a file.
Click here to check if an image exists from a URL in PHP.
1 2 3 4 5 6 7 8 9 10 | <?php // Image URL $url = 'https://www.example.com/test.png'; // Image path $img = '../images/test.png'; // Save image file_put_contents($img, file_get_contents($url)); ?> |
2. Using cURL function
We can use the cURL function to copy an image from URL in PHP as shown in the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php // Image URL $url = 'https://www.example.com/test.png'; // Image path $img = '../images/test.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 for today.
Thank you for reading. Happy Coding..!!