/**
* 下載遠程圖片
* @param string $url 圖片的絕對url
* @param string $filepath 文件的完整路徑(例如/www/images/test) ,此函數會自動根據圖片url和http頭信息肯定圖片的後綴名
* @param string $filename 要保存的文件名(不含擴展名)
* @return mixed 下載成功返回一個描述圖片信息的數組,下載失敗則返回false
*/
static
public
function
downloadImage(
$url
,
$filepath
,
$filename
) {
//服務器返回的頭信息
$responseHeaders
=
array
();
//原始圖片名
$originalfilename
=
''
;
//圖片的後綴名
$ext
=
''
;
$ch
= curl_init(
$url
);
//設置curl_exec返回的值包含Http頭
curl_setopt(
$ch
, CURLOPT_HEADER, 1);
//設置curl_exec返回的值包含Http內容
curl_setopt(
$ch
, CURLOPT_RETURNTRANSFER, 1);
//設置抓取跳轉(http 301,302)後的頁面
curl_setopt(
$ch
, CURLOPT_FOLLOWLOCATION, 1);
//設置最多的HTTP重定向的數量
curl_setopt(
$ch
, CURLOPT_MAXREDIRS, 3);
//服務器返回的數據(包括http頭信息和內容)
$html
= curl_exec(
$ch
);
//獲取這次抓取的相關信息
$httpinfo
= curl_getinfo(
$ch
);
curl_close(
$ch
);
if
(
$html
!== false) {
//分離response的header和body,因爲服務器可能使用了302跳轉,因此此處須要將字符串分離爲 2+跳轉次數 個子串
$httpArr
=
explode
(
"\r\n\r\n"
,
$html
, 2 +
$httpinfo
[
'redirect_count'
]);
//倒數第二段是服務器最後一次response的http頭
$header
=
$httpArr
[
count
(
$httpArr
) - 2];
//倒數第一段是服務器最後一次response的內容
$body
=
$httpArr
[
count
(
$httpArr
) - 1];
$header
.=
"\r\n"
;
//獲取最後一次response的header信息
preg_match_all(
'/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/i'
,
$header
,
$matches
);
if
(!
empty
(
$matches
) &&
count
(
$matches
) == 3 && !
empty
(
$matches
[1]) && !
empty
(
$matches
[1])) {
for
(
$i
= 0;
$i
<
count
(
$matches
[1]);
$i
++) {
if
(
array_key_exists
(
$i
,
$matches
[2])) {
$responseHeaders
[
$matches
[1][
$i
]] =
$matches
[2][
$i
];
}
}
}
//獲取圖片後綴名
if
(0 < preg_match(
'{(?:[^\/\\\\]+)\.(jpg|jpeg|gif|png|bmp)$}i'
,
$url
,
$matches
)) {
$originalfilename
=
$matches
[0];
$ext
=
$matches
[1];
}
else
{
if
(
array_key_exists
(
'Content-Type'
,
$responseHeaders
)) {
if
(0 < preg_match(
'{image/(\w+)}i'
,
$responseHeaders
[
'Content-Type'
],
$extmatches
)) {
$ext
=
$extmatches
[1];
}
}
}
//保存文件
if
(!
empty
(
$ext
)) {
//若是目錄不存在,則先要建立目錄
if
(!
is_dir
(
$filepath
)){
mkdir
(
$filepath
, 0777, true);
}
$filepath
.=
'/'
.
$filename
.
".$ext"
;
$local_file
=
fopen
(
$filepath
,
'w'
);
if
(false !==
$local_file
) {
if
(false !== fwrite(
$local_file
,
$body
)) {
fclose(
$local_file
);
$sizeinfo
=
getimagesize
(
$filepath
);
return
array
(
'filepath'
=>
realpath
(
$filepath
),
'width'
=>
$sizeinfo
[0],
'height'
=>
$sizeinfo
[1],
'orginalfilename'
=>
$originalfilename
,
'filename'
=>
pathinfo
(
$filepath
, PATHINFO_BASENAME));
}
}
}
}
return
false;
}
|