Search code examples
phpimagedetectcorrupt

Is there any way to have PHP detect a corrupted image?


Is there any way to have PHP determine whether an image file is corrupted and will not be able to display properly?

I've tried to check with fopen and check whether the URL is valid, but it hasn't worked!


Solution

  • Javascript solution (with involving jQuery, though this should be possible to do without it too):

    <script type='text/javascript'>
        $(function(){
            var files = [
                'warning-large.png',
                'warning-large-corrupted.png',
                'http://www.example.com/none.gif',
                'http://sstatic.net/stackoverflow/img/favicon.ico'
            ];
            for ( var n in files ) {
                var img = $('<img/>');
                img.error(function(){
                    alert('error:\n' + this.src);
                });
                img.load(function(){
                    alert('success:\n' + this.src);
                });
                img.attr('src', files[n]);
            }
        });
    </script>