Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 350
Piotr Avatar asked Jul 04 '11 06:07

Piotr


Video Answer


3 Answers

Is there any way to have PHP determine whether an image file is broken

If by broken you mean corrupted, changes are the imagecreatefrom{extension} won't be able to read them either:

if( imagecreatefromjpeg( $yourfile ) !== false ) {
    // image is okay.
}
like image 181
Berry Langerak Avatar answered Oct 29 '22 14:10

Berry Langerak


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>
like image 28
binaryLV Avatar answered Oct 29 '22 14:10

binaryLV


If you mean broken as in a 404, and not a corrupt image, you can always use something along the lines of:

if (file_exists($imageFileName)) {
  ..
}
like image 31
jerluc Avatar answered Oct 29 '22 14:10

jerluc