array url_image_size(string url)
- uses getimagesize() to determine the size of a file.
- attempts to connect to the server first so it won't time out.
- returns false on failure, otherwise the output of getimagesize().
โค้ด: เลือกทั้งหมด
function url_image_size($url)
{
global $sourcedir;
// Can we pull this from the cache... please please?
if (($temp = cache_get_data('url_image_size-' . md5($url), 240)) !== null)
return $temp;
$t = microtime();
// Get the host to pester...
preg_match('~^\w+://(.+?)/(.*)$~', $url, $match);
// Can't figure it out, just try the image size.
if ($url == '' || $url == 'http://' || $url == 'https://')
return false;
elseif (!isset($match[1]))
$size = @getimagesize($url);
else
{
// Try to connect to the server... give it half a second.
$temp = 0;
$fp = @fsockopen($match[1], 80, $temp, $temp, 0.5);
// Successful? Continue...
if ($fp != false)
{
// Send the HEAD request (since we don't have to worry about chunked, HTTP/1.1 is fine here.)
fwrite($fp, 'HEAD /' . $match[2] . ' HTTP/1.1' . "\r\n" . 'Host: ' . $match[1] . "\r\n" . 'User-Agent: PHP/SMF' . "\r\n" . 'Connection: close' . "\r\n\r\n");
// Read in the HTTP/1.1 or whatever.
$test = substr(fgets($fp, 11), -1);
fclose($fp);
// See if it returned a 404/403 or something.
if ($test < 4)
{
$size = @getimagesize($url);
// This probably means allow_url_fopen is off, let's try GD.
if ($size === false && function_exists('imagecreatefromstring'))
{
include_once($sourcedir . '/Subs-Package.php');
// It's going to hate us for doing this, but another request...
$image = @imagecreatefromstring(fetch_web_data($url));
if ($image !== false)
{
$size = array(imagesx($image), imagesy($image));
imagedestroy($image);
}
}
}
}
}
// If we didn't get it, we failed.
if (!isset($size))
$size = false;
// If this took a long time, we may never have to do it again, but then again we might...
if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $t)) > 0.8)
cache_put_data('url_image_size-' . md5($url), $size, 240);
// Didn't work.
return $size;
}