1. PHP

PHP – Save Image from URL

You have an image in a URL, something like “https://www.lab-informatika.com/images/sample.png“, and you want to save that image in your computer, but you want to obtain that directly from PHP. How to do that? Saving images from any live url is very easy with php. Here are three ways to do this.

  1. Using Curl
  2. Using File functions
  3. Using GD library functions.

Using Curl

To use this method, CURL extension needs to be installed in your php environment. So here is the function for grabbing and saving an image using Curl.

function save_image($url, $output) 
    $ch = curl_init($url);  
    curl_setopt($ch, CURLOPT_HEADER, 0);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);  
    $raw = curl_exec($ch);  
    if (file_exists($output)) {  
    $fp = fopen($output, 'x');  
    fwrite($fp, $raw);  

Using File functions

function save_image($url, $output) 
    $in = fopen($url, "rb");
    $out = fopen($output, "wb");
    while ($chunk = fread($in,8192))
        fwrite($out, $chunk, 8192);

Using GD library functions.

To use this method, you have to set allow_url_fopen to on. The allow_url_fopen directive is disabled by default.

function save_image($url, $output) 
    $img = imagecreatefromjpeg($url);
    imagejpeg($img, $output);

How to use

Now, we can save any images from live URL using below command.

save_image("https://www.lab-informatika.com/images/sample.jpg", "path/sample.jpg")

Comments to: PHP – Save Image from URL

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

    Attach images - Only PNG, JPG, JPEG and GIF are supported.