Home > Article > Backend Development > Get a remote image and save it locally_PHP tutorial
//
// Function: Get the remote image and save it locally
//
//
// Make sure you have Permission to write files to the local server
//
//
// Variable description:
// $url is the complete URL address of the remote image and cannot be empty.
// $filename is an optional variable: if empty, the local file name will be automatically generated based on time and date
//.
function GrabImage($url,$filename="") {
if($url==""):return false;endif;
if($filename=="") {
$ext=strrchr($url,".");
if($ext!=".gif" && $ext!=".jpg"):return false;endif;
$filename=date("dMYHis").$ext;
}
ob_start();
readfile($url);
$img = ob_get_contents();
ob_end_clean();
$size = strlen($img);
$fp2=@fopen($filename, "a");
fwrite($fp2,$img);
fclose($fp2);
return $filename;
}
$img=GrabImage("http://news.bbc.co.uk/images/_1978837_detector_ap100.jpg","");
if($img):echo '
<img src="'.$img.'">';