PHP to obtain the image in the web page and save to the local code

  • 2020-03-31 20:17:10
  • OfStack


<?php 
header("Content-type:image/jpeg"); 
function read_url($str) 
{ 
$file=fopen($str,"r"); 
while(!feof($file)) 
{ 
$result.=fgets($file,9999); 
} 
fclose($file); 
return $result; 

} 

function save_img($str) 
{ 
$result=read_url($str); 
$result=str_replace(""","",$result); 
$result=str_replace("'","",$result); 

preg_match_all('/<imgssrc=(http://.*?)(s(.*?)>|>)/i',$result,$matches); 

foreach($matches[1] as $value) 
{ 
echo $value."<br>n"; 
//GrabImage($value,$filename=""); 
} 
} 

//$url is the full url address of the remote image and cannot be null.
//$filename is an optional variable: if empty, the local filename is based on time and date
//Automatic generation.

function GrabImage($url,$filename="") { 
if($url==""):return false;endif; 

$path="download/"; //Specify storage folder

//If the file does not exist, it is created.
if(!file_exists($path)){ 
mkdir($path); 
} 

if($filename=="") { 
$ext=strrchr($url,"."); 
if($ext!=".gif" && $ext!=".jpg"):return false;endif; 
$filename=$path.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; 
} 
save_img("//www.jb51.net"); 
?> 

Related articles: