How to save image from a url in laravel?

In this post we will learn how to save image form a url in laravel, We will be using laravel storage functionality to save the file, But first we'll need to retrive image data or image content form url and extract image extension, So to do that we will use multiple php functions.


Lets get started, First we need to create a new disk to store our image, To create a new disk goto /config/filesystems.php

Note :  You can also use default disk which is local.

'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => storage_path('app'),
        'throw' => false,
    ],

    'images' => [
        'driver' => 'local',
        'root' => storage_path('uploads/images'),
        'throw' => false,
    ],
$imageUrl = 'url_here';
    
$sizeData = getimagesize($imageUrl);
$extension = image_type_to_extension($sizeData[2]);

$imageName = time() . rand(1,9999) . $extension;
Storage::disk('images')->put($imageName, file_get_contents($imageUrl));

`file_get_contents` is a function in PHP that reads the contents of a file into a string. It's the preferred way to read the contents of a file into a string as it uses memory mapping techniques, if supported by the server, to enhance performance.

Please note that if you're opening a URI with special characters, such as spaces, you need to encode the URI with `urlencode()`.


The `getimagesize()` function in PHP is used to determine the size of an image file. It returns the dimensions of the image along with the file type and a height/width text string that can be used inside a normal HTML IMG tag.


The `image_type_to_extension()` function in PHP is used to get the file extension for an image type. 


Here's the syntax of the function :

string image_type_to_extension ( int $imagetype, bool $include_dot )


- `$imagetype`: This parameter accepts an integer value that is one of the IMAGETYPE_XXX constants, such as IMAGETYPE_GIF, IMAGETYPE_JPEG, etc.

- `$include_dot`: This boolean parameter decides whether to prepend a dot to the extension or not. The default value is set to TRUE.


The function returns a string value associated with the extension corresponding to the given image type. For example, if you pass IMAGETYPE_PNG as the `$imagetype` and TRUE as the `$include_dot`, the function will return '.png'.