How to Save Image From URL Using PHP

Today I will share with you simple php code snippet how to save image from external url to your server using PHP. For example, we will save our facebook and twitter avatar to our server.

<?php
function save_image($inPath,$outPath){
	//Download images from remote server
    $in=    fopen($inPath, "rb");
    $out=   fopen($outPath, "wb");
    while ($chunk = fread($in,8192))
    {
        fwrite($out, $chunk, 8192);
    }
    fclose($in);
    fclose($out);
}
save_image('http://graph.facebook.com/100000881073253/picture','facebook.jpg');
save_image('http://a0.twimg.com/profile_images/457031171/favicoblogfreakz_bigger.png','twitter.jpg');
?>

Alternatif code

If you have allow_url_fopen set to true:

$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));

Else use cURL:

$ch = curl_init('http://example.com/image.php');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

Source : http://stackoverflow.com/questions/724391/save-image-from-php-url-using-php

Incoming search terms for the article: