Home >Backend Development >PHP Tutorial >How to use PHP to grab remote images and save them as_PHP Tutorial
The following is the source code and related explanations
//URL is the complete remote image address and cannot be empty. $filename is the name of the image saved as
//Place the image in the same directory as this script by default
Function GrabImage($url, $filename=""){
// Return false if $url is empty;
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";}//Rename with timestamp
// Start capturing
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("http://www.66xing.com/UploadFile/200609082320515027.bmp", "as.gif");
?>
Related description:
ob_start: Turn on output buffering
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. (Output is stored in an internal buffer)
//
readfile: Read a file and write it to the output buffer
Returns the number of bytes read from the file. Returns FALSE on error and displays an error message unless called as @readfile().
//
ob_get_contents: Return the contents of the output buffer(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(clear the output buffer)
This function discards(discard) the contents of the topmost output buffer and turns off this output buffering.(discard and turn off) 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 buffer contents are to be used, ob_get_contents() must be called before cleaning the output buffer) first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).