PHP: Save Image From URL

Posted on
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.

1. Using PHP function file_get_contents()

$contents = file_get_contents('');

2. Using fsockopen() PHP 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 GetImgFromHost($host,$link) { $fp = fsockopen($host, 80, $errno, $errstr, 30); if (!$fp) { echo "$errstr (Error: $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=GetImgFromHost("","/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 can use this code to call the function to get the source of the image:

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);
Free Hit Counters