Hello everyone, starting today, the younger brother began to write blog, the problem of their work encountered in the resolution of the record down, convenient for later search, but also to give others convenient, younger brother, the first blog, what shortcomings please point out, thank you!
Today's record is how to remotely download images to the local via PHP, not much nonsense to say, on the code.
<?php
/*
* Function: PHP perfect implementation download remote picture saved to local
* Parameters: File URL, save file directory, save file name, use the download method
* Use the original name of the remote file when the save file name is empty
*/
function GetImage ($url, $save _dir= ", $filename =", $type =0) {
if (Trim ($url) = = ") {
Return Array (' file_name ' = ' = ', ' save_path ' = ' = ', ' ERROR ' =>1);
}
if (Trim ($save _dir) = = ") {
$save _dir= './';
}
if (Trim ($filename) = = ") {//Save file name
$ext =strrchr ($url, '. ');
if ($ext! = '. gif ' && $ext! = '. jpg ') {
Return Array (' file_name ' = ' = ', ' save_path ' = ' = ', ' ERROR ' =>3);
}
$filename =time (). $ext;
}
if (0!==strrpos ($save _dir, '/')) {
$save _dir.= '/';
}
Create a Save directory
if (!file_exists ($save _dir) &&!mkdir ($save _dir,0777,true)) {
Return Array (' file_name ' = ' = ', ' save_path ' = ' = ', ' ERROR ' =>5);
}
Methods used to get remote files
if ($type) {
$ch =curl_init ();
$timeout = 5;
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, curlopt_returntransfer,1);
curl_setopt ($ch, Curlopt_connecttimeout, $timeout);
$img =curl_exec ($ch);
Curl_close ($ch);
}else{
Ob_start ();
ReadFile ($url);
$img =ob_get_contents ();
Ob_end_clean ();
}
$size =strlen ($IMG);
File size
[Email protected] ($save _dir. $filename, ' a ');
Fwrite ($fp 2, $img);
Fclose ($fp 2);
Unset ($img, $url);
Return Array (' file_name ' = $filename, ' save_path ' = $save _dir. $filename, ' error ' =>0);
}
?>
Then directly call the function to download the image to the local
$img = GetImage ("$url", "images/");
PHP remote download images to local