Jump to content

PHP Detect Broken Image


drath

Recommended Posts

I've used this function I made up before

<?php
is_img($img_path){
$image_types = array("image/jpeg", "image/jpg", "image/pjpg", "image/pjpeg", "image/gif", "image/pgif", "image/png", "image/ppng");
$data = getimagesize($img_path);
if(in_array($data[3],$image_types)){
	return TRUE;
}
else{
	return FALSE;
}
}
?>

 

If its a valid image type it returns true else its false

Hmm, I never knew about getimagesize before, it seems to be working. The only issue I am having is it will print an warning/error when it can't find the image (when it's actually broken). Is there any way to handle the error and create a custom echo or something? I've never error handled before in PHP.

us it in a if command

example

<?php
#assume the function is in this file (the is_img function I wrote)
$img = new Img_Class
if(is_img($img->path)){
#its good do what you want
}
else{
#use your custom class error reporting
$img->error_report("Its a broken image");
}
?>

 

Get it?

Hmmm, well it just tried both the methods and ukwntech's file method seems to be much faster. Perhaps my server is just slow with PHP, but the imagegetsize really seems to get slow at some points. There does however seem to be a flaw using the file method... it doesn't detect if it's forbidden... although I suspect that would be a problem with the imagegetsize as well. Any ideas for blocking forbidden images?

Actually, both the methods you guys supplied result in one thing:

 

Slowness rendering the page.

 

The reason is, because I am trying to find images one after another which means if it can't find one, it will stop the whole page until it's sure it's not available (based on timeout?). Both methods also mean it will check on each image which may be fast or slow depending on the host of the image, some take a long time to respond.

 

I now currently use a javascript that will replace the broken image after everything is loaded instead of PHP trying to check one by one. It's speed is incredibly faster; however, I don't have the flexibility of PHP rendering custom messages and stuff when they fail, which is why I still want a PHP method that is faster... I just can't get it to do so :).

 

*EDIT*

 

One idea would be to let PHP load all the images in, then check each image after, and then somehow replace the information (the div and img tags) with nothing, or blank. Although, I wouldn't know how to replace already echo'd information.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.