I think the following routine will retrieve just the image heights for JPG, GIF, and PNG, or return an === FALSE condition on a 404 or other image type. The routine also does this with the least server resources because the file_get_contents() route appears to actually download the file even with byte restriction added in, as does getimagesize() download the file. You can see the performance hit compared to this.
The way this routine works is that it downloads just 300 bytes from the file. Unfortunately JPEG pushes its height value pretty far out in a file unlike GIF or PNG and so I had to read the file that far out in bytes. Then, with those bytes, it scans for JFIF, PNG, or GIF in that header to let us know which file type it is. Once we have that, we then use unique routines on each to parse the header. Note that JPEG must first use unpack() with H* and then scan for ffc2 or ffc0 and process. GIF, however, must first unpack() with h* (big difference there).
This function was created by me with trial and error, and could be wrong. I ran it on several images and it appears to work good. If you find a fault in it, consider letting me know.
Anyway, this system will let me determine an image height and discard the image and find another if too tall. On whatever random image I find, I set width in the IMG tag of the HTML and it automatically resizes the height -- but looks good only if the image is under a certain height. As well, it does a 404 check to see if the image that was returned by another server to me was not for an image that no longer exists or which prohibits cross-site linking. And since I am manually setting the images to a fixed width, I don't care to read the image width. You can adapt this function and usually look just a few small bytes forward to find image widths should you want to do so.
function getImageHeight($sURL) {
try {
$hSock = @ fopen($sURL, 'rb');
if ($hSock) {
while(!feof($hSock)) {
$vData = fread($hSock, 300);
break;
}
fclose($hSock);
if (strpos(' ' . $vData, 'JFIF')>0) {
$vData = substr($vData, 0, 300);
$asResult = unpack('H*',$vData);
$sBytes = $asResult[1];
if (strstr($sBytes, 'ffc2')) {
$sBytes = substr($sBytes, strpos($sBytes, 'ffc2') + 10, 4);
} else {
$sBytes = substr($sBytes, strpos($sBytes, 'ffc0') + 10, 4);
}
return hexdec($sBytes);
} elseif (strpos(' ' . $vData, 'GIF')>0) {
$vData = substr($vData, 0, 300);
$asResult = unpack('h*',$vData);
$sBytes = $asResult[1];
$sBytes = substr($sBytes, 16, 4);
$sBytes = strrev($sBytes);
return hexdec($sBytes);
} elseif (strpos(' ' . $vData, 'PNG')>0) {
$vData = substr($vData, 22, 4);
$asResult = unpack('n',$vData);
$nHeight = $asResult[1];
return $nHeight;
}
}
} catch (Exception $e) {}
return FALSE;
}