I know that there are at least 10 the same questions with answers but none of them seems to work for me flawlessly. I'm trying to check if internal or external image exists (is image URL valid?).
fopen($url, 'r')
fails unless I use@fopen()
:Warning: fopen(http://example.com/img.jpg) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in file.php on line 21
getimagesize($img)
fails when image doesn't exist (PHP 5.3.8):Warning: getimagesize() [function.getimagesize]: php_network_getaddresses: getaddrinfo failed
- CURL fails because it isn't supported by some servers (although it's present mostly everywhere).
fileExists()
fails because it doesn't work with external URLs and can't possibly check if we're dealing with image.
Four methods that are the most common answers to such question are wrong. What would be the correct way to do that?
You can use the PEAR/HTTP_Request2 Package for this. You can find it here
Here comes an example. The Example expects that you have installed or downloaded the HTTP_Request2 package properly. It uses the old style socket adapter, not curl.
Use
fsockopen
, connect to the server, send aHEAD
request and see what status you get back.The only time you need to be aware of problems is if the domain doesn't exist.
Example code:
I found try catch the best solution for this. It is working fine with me.
There are multiple steps, there is no single solution:
For this kind of work you can catch the exceptions and handle them well to define your answer. In this case you could even suppress errors because it's intended that they trick might fail. So you handle the errors correctly.
Because it's not possible to do a 100% check on it without having the actual image downloaded. So step 1 and 2 are required, 3 and 4 optional for a more definitive answer.
If you're using PHP >=5.0.0 you can pass an additional parameter into fopen to specify context options for HTTP, among them whether to ignore failure status codes.