Save Image from URL

alfa6661
- October 02, 2013
0 (0 votes)
Rate :
How to save image from remote url using PHP

You have an image in a URL, something like "http://www.lab-informatika.com/images/sample.jpg", 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);  
    curl_close($ch);  
    if (file_exists($output)) {  
        unlink($output);  
    }  
    $fp = fopen($output, 'x');  
    fwrite($fp, $raw);  
    fclose($fp);  
}

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);
    }
    fclose($in);
    fclose($out);
}

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

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

Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter

– Eric S. Raymond

Have a better explanation?

If you have comments about this post. Please write your comments below

No comments associated with this article