Download Source Code

You can save image from url in PHP you should first get thesource of the image from the url  and after that save image to your server or disk depending on where you execute the php script.

First for getting an image from url you can use three ways to do this:

1. Using file_get_contents

$contents= file_get_contents('http://mydomain.com/folder/image.jpg');

2. Using fsockopen() function

To fetch an image with fsockopen() You should specify the host name of the server and the the rest or the url where the image is stored. To understand better here is a sample function, that takes the  that returns the source code of the image:

 
function GetImg($host,$link)
{
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr (error number $errno)
\n";
} else {
$out = "GET $link HTTP/1.1\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n\r\n";
$out .= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
$out .= "Accept-Language: en-us,en;q=0.5\r\n";
$out .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
$out .= "Keep-Alive: 300\r\n";   
$out .= "\r\n";
fwrite($fp, $out);
$contents='';
while (!feof($fp)) {
$contents.= fgets($fp, 1024);
}
fclose($fp);
return $contents;
}
}

Example call: 

$sourceimg=GetImg("www.mywebsiteexample.com","/image.jpg");
$sourceimg=strchr($sourceimg,"\r\n\r\n");//removes headers
$sourceimg=ltrim($sourceimg);//remove whitespaces from begin of the string

3.Using CURL

function GetImageFromUrl($link)
 
{
 
$ch = curl_init();
 
curl_setopt($ch, CURLOPT_POST, 0);
 
curl_setopt($ch,CURLOPT_URL,$link);
 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
$result=curl_exec($ch);
 
curl_close($ch);
 
return $result;
 
}

You should have installed at least  PHP 4.0.2. and libcurl installed to use curl.

Here is a function that will get the source of the image into a string variable:

You can use this code to call the function to get the source of the image:

$sourcecode=GetImageFromUrl("http://domain.com/path/image.jpg");

 

After getting the image from url you should save image from url, doing a simple save to file from  a string variable.

You can use this piece of code:

$savefile = fopen('/home/path/image.jpg', 'w');
fwrite($savefile, $sourcecode);
fclose($savefile);

Download Source Code for Saving Image From Url