PHPのリモート画像のダウンロード
3587 ワード
/**
*
* @param string $url url
* @param string $filepath ( /www/images/test) , url http
* @param string $filename ( )
* @return mixed , false
*/
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
\r
", $html, 2 + $httpinfo['redirect_count']);
// response http
$header = $httpArr[count($httpArr) - 2];
// response
$body = $httpArr[count($httpArr) - 1];
$header .= "\r
";
// response header
preg_match_all('/([a-z0-9-_]+):\s*([^\r
]+)\r
/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 array('orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, PATHINFO_BASENAME));
}
}
}
}
return false;
}