Saving an Image from URL in PHP/Laravel

Sometimes, need to download an image from a particular URL and use it in 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 from person to person, developer to developer. If the set of hundreds of image URLs is given and somehow wants to save them into the machine, or need to use this concept in the projects. Then definitely not going to download each one of those files manually.

There are two different approaches to download images 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 the 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 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.
$url = 
$img = 'logo.png'; 
// Function to write image into file
file_put_contents($img, file_get_contents($url));
echo "File downloaded!"

I hope it will help you.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button