Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct PHP way to check if external image exists?

Tags:

php

image

exists

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?).

  1. 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
    
  2. getimagesize($img) fails when image doesn't exist (PHP 5.3.8):

    Warning: getimagesize() [function.getimagesize]: php_network_getaddresses: getaddrinfo failed
    
  3. CURL fails because it isn't supported by some servers (although it's present mostly everywhere).
  4. 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?

like image 343
Atadj Avatar asked Dec 19 '12 16:12

Atadj


2 Answers

getimagesize($img) fails when image doesn't exist: am not sure you understand what you want .....

FROM PHP DOC

The getimagesize() function will determine the size of any given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag and the correspondant HTTP content type.

On failure, FALSE is returned.

Example

$img = array("http://i.stack.imgur.com/52Ha1.png","http://example.com/img.jpg");
foreach ( $img as $v ) {
    echo $v, getimagesize($v) ? " = OK  \n" : " = Not valid \n";
}

Output

http://i.stack.imgur.com/52Ha1.png = OK  
http://example.com/img.jpg = Not valid 

getimagesize works just fine

  • PHP 5.3.19
  • PHP 5.4.9

Edit

@Paul .but your question is essentially saying "How do I handle this so I won't get an error when there's an error condition". And the answer to that is "you can't". Because all these functions will trigger an error when there is an error condition. So (if you don't want the error) you suppress it. None of this should matter in production because you shouldn't be displaying errors anyway ;-) – DaveRandom

like image 185
Baba Avatar answered Sep 21 '22 02:09

Baba


This code is actually to check file... But, it does works for images!

$url = "http://www.myfico.com/Images/sample_overlay.gif";
$header_response = get_headers($url, 1);
if ( strpos( $header_response[0], "404" ) !== false )
{
   // FILE DOES NOT EXIST
} 
else 
{
   // FILE EXISTS!!
}
like image 27
sk8terboi87 ツ Avatar answered Sep 21 '22 02:09

sk8terboi87 ツ