PHP remote image capture function share

  • 2020-09-16 07:25:23
  • OfStack

 
function grabImage($url, $filename = '') { 
if($url == '') { 
return false; // if  $url  Returns if null  false; 
} 
$ext_name = strrchr($url, '.'); // Gets the extension for the image  
if($ext_name != '.gif' && $ext_name != '.jpg' && $ext_name != '.bmp' && $ext_name != '.png') { 
return false; // The format is not allowed  
} 
if($filename == '') { 
$filename = time().$ext_name; // I'm going to call it a timestamp  
} 
// To capture  
ob_start(); 
readfile($url); 
$img_data = ob_get_contents(); 
ob_end_clean(); 
$size = strlen($img_data); 
$local_file = fopen($filename , 'a'); 
fwrite($local_file, $img_data); 
fclose($local_file); 
return $filename; 
} 

Related articles: