PHP Detecting if source image url link leads to a "broken" image?

Viewed 22292

Suppose you have a thumbnail generator script that accepts source images in the form of a URL. Is there a way to detect if the source URL is "broken" - whether nonexistent or leads to an non-image file?


Just brute force using getimagesize() or another PHP GD function is not a solution, since spoofed stray URL's that might not be images at all (http://example.com/malicious.exe or the same file, but renamed as http://example.com/malicious.jpg) could be input - such cases could easily be detected by PHP before having to invoke GD. I'm looking for GD pre-sanitizing before having GD try its battalion at parsing the file.


as a first step, the following regular expression checks if the URL is an image extension: preg_match('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)([^\s]+(\.(?i)(jpg|png|gif|bmp))$)@', $txt,$url);

9 Answers

onerror Event

Execute a JavaScript if an error occurs when loading an image:

The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).

Example:

<!DOCTYPE html>
<html>
<body>

<img src="image.gif" onerror="myFunction()">

<p>A function is triggered if an error occurs when loading the image. The function shows an alert box with a text.
In this example we refer to an image that does not exist, therefore the onerror event occurs.</p>

<script>
function myFunction() {
  alert('The image could not be loaded.');
}
</script>

</body>
</html>

Although not detecting broken links, might be useful for someone else...

onerror=""

<img src="PATH" onerror="this.src='NEW PATH'" />
Related