Sometimes we need to download an image from a URL to use in the project. Though we can easily download an image from another URL just by right click on the image and save.
But what if you have to do the same for hundreds of images. What if you are given hundreds of image URLs and asked to download all images, then you have to download all images one by one, and that would be very boring work to do.
What if you have PHP function to save the image from URL to folder. What if you have a function for this particular type of problem and by using you can finish this task in a minute.
Below function you can use to grab an image from URL in PHP.
function grab_remote_pic($new_file_name, $local_dir_path, $remote_picture_url) { if(!is_dir($local_dir_path)){ //create new dir if doesn't exist mkdir($local_dir_path); } $local_file_path = $local_dir_path .'/'.$new_file_name; if(copy($remote_picture_url, $local_file_path)) { return true; } }
Usage :
//grab_remote_pic(NEW FILE NAME, LOCAL SAVE PATH, REMOTE IMAGE URL) grab_remote_pic('newFileName.gif', 'images/', 'https://atcodex.com/wp-content/uploads/2020/05/2936875814_45991885-112e-4fa1-9167-f15f07490f95-e1588431067659-1.png'); echo "<img src='images/newFileName.gif'>";
Hope it will help