onerror image not displayed when image does not exist

181 views Asked by At

I'm using this code:

function base64_encode_image ($filename=string,$filetype=string) {
    if ($filename) {
        $imgbinary = fread(fopen($filename, "r"), filesize($filename));
        return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
    }
}}


<img src="<?php echo base64_encode_image ('img/123.jpg','jpg'); ?>" alt='' onerror="this.onerror=null;this.src='img/no-image.jpg';"/>

The problem is that the onerror image (no-image.jpg) is not showing although 123.jpg image does not exist.

I get the following error message: Warning: filesize(): stat failed for img/123.jpg

Any help would be appreciated.

1

There are 1 answers

0
Blaatpraat On

You're mixing up PHP and javascript.
Best way is to fix this in your PHP function.

For example:

function base64_encode_image ($filename=string,$filetype=string) {
    if (!$filename || !file_exists($filename)) {
        $filename = 'img/no-image.jpg';
        $filetype = 'jpg';
    }

    $imgbinary = fread(fopen($filename, "r"), filesize($filename));
    return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}

If the file does not exists, it will take the no-image.jpg here. In your output, you can drop the onerror:

<img src="<?php echo base64_encode_image ('img/123.jpg','jpg'); ?>" alt='' />