问题
I have this situation where I have some pictures:
http://www.example.com/test1.jpg
http://www.example.com/test2.jpg
http://www.example.com/test3.jpg
....
some of them might be dead links and the image will not show up, but a small broken
icon.
I am doing this to check for those images:
if(!is_array(getimagesize($mediapath))){
$mediapath = '';
}
return $mediapath;
Basically getimagesize
gets the image size of a image :), and returns an array. If the image is broken it errors out.
And this is my problem. The code does the job ok, but now I get error telling me that some files don't exist:
Warning: getimagesize(http://www.example.com/test2.jpg) [function.getimagesize]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in C:\xampp\htdocs\zend\models\mappers\search.php on line 173
But this is the desired result, I just dont want those errors on the page, And no, I don't want to disable errors in PHP, I want the 'getimagesize' method not to show that error.
回答1:
There are very rare cases where the error suppression operator is not evil, this is one of them.
if(@!is_array(getimagesize($mediapath))){
$mediapath = '';
}
return $mediapath;
Note the @
prefixing the statement. It will cause any error, warning or notice be suppressed. Be advised that if a fatal error occurs, the script will terminate without giving indication!
回答2:
You can use the get_headers function in that situation:
$url = 'http://www.example.com/test1.jpg';
print_r(get_headers($url));
It will report back an array like this:
Array
(
[0] => HTTP/1.1 200 OK
[1] => Date: Sat, 29 May 2004 12:28:13 GMT
[2] => Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
[3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
[4] => ETag: "3f80f-1b6-3e1cb03b"
[5] => Accept-Ranges: bytes
[6] => Content-Length: 438
[7] => Connection: close
[8] => Content-Type: text/html
)
You can use that http response to know whether image exists or not :)
回答3:
That's a hideously inefficient method of testing. PHP has to download the entire image before it can pass the file's contents to getimagesize().
You'd better off using curl. Issue a HEAD
request for each url, and see if you get a 200 or 404 response. That's relatively cheap, and would only be one TCP connection and a few packets for each URL (say, 4k of data transfer), v.s. 200+k for each full image file.
来源:https://stackoverflow.com/questions/9301174/how-to-find-if-an-image-exists-or-renders-ok-issue-in-php