PHP to grab web images and save as the implementation code

  • 2020-03-31 20:33:20
  • OfStack

The following is the source code and its explanation
 
<?php 
//The URL is the remote full image address, cannot be empty, and $filename is the image name saved as
//By default, images are placed in the same directory as this script
function GrabImage($url, $filename=""){ 
//If the $url is empty, it returns false.
if($url == ""){return false;} 
$ext = strrchr($url, ".");//Get the extension of the image
if($ext != ".gif" && $ext != ".jpg" && $ext != ".bmp"){echo " Format not supported! ";return false;} 
if($filename == ""){$filename = time()."$ext";}//Name it with a timestamp
//To capture
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; 
} 
//test
GrabImage("//www.jb51.net/images/logo.gif", "as.gif"); 
?> 

Ob_start: opens the output buffer
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead of the output is stored in an internal buffer.
//
Readfile: reads a file and writes to the output buffer
Returns the number of bytes read from the file. Returns FALSE on an error and displays an error message unless called as @readfile().
//

Ob_get_contents: Return the contents of the output buffer
This will return the contents of the output buffer without clearing it or FALSE, if output buffering isn't active.
//
Ob_end_clean () : Clean (erase) the output buffer and turn off output buffering
This function discards the contents of the topmost output buffer and turns off This output buffering. If you want to further process the buffer's contents you have to call Ob_get_contents () before ob_end_clean () as the buffer contents are discarded when ob_end_clean () is called. (if you want to use the buffer content, In cleaning The output buffer before The first call ob_get_contents ()), The function returns TRUE The when it successfully discarded one buffer and FALSE otherwise. Having The for failure are The first that called The function without an active Buffer or that for some reason a buffer could not be deleted (possible for special buffer).

Related articles: