PHP GD image not displaying in Chrome

3.2k Views Asked by At

We have used Captcha.php on one of our project, it opens in all browsers but we are not able to view in Google chrome Version 22.

Our Captcha script

session_start();
$captcha = new SimpleCaptcha();
$captcha->CreateImage();

class SimpleCaptcha 
{
    function CreateImage()
    {
        header("Content-Type: image/jpeg");

        $md5              = md5(rand(0,9999));
        $pass             = substr($md5, 10, 5);
        $_SESSION["pass"] = $pass;

        $image     = ImageCreatetruecolor(100, 20);
        $clr_white = ImageColorAllocate($image, 0, 0, 0);
        $clr_black = ImageColorAllocate($image, 255, 255, 255);

        imagefill($image, 0, 0, $clr_white);
        imagefontheight(15);
        imagefontwidth(15);
        imagestring($image, 5, 30, 3, $pass, $clr_black);

        return imagejpeg($image);
        imagedestroy($image);
    }
}

HTML Implementation

<img src="code/captcha.php" width="100" height="20" alt="Captcha Code"/>

We are not able to view it on Google Chrome. All the browser return the same image.

5

There are 5 best solutions below

0
On

It may be to do with caching, I've used this a script of mine:

header('Cache-Control: no-cache, must-revalidate');

Just that line should be enough.

0
On

I have faced same problem. Just turned off my kaspersky. It is working fine now. You can also try this.

0
On

There is a known issue that materializes between Chrome & some versions of Kaspersky.

Kaspersky Anti-Virus doesn't cause it, but Kaspersky Endpoint Security does.

For some reason, during the interaction of the two applications when retrieving dynamically created images from the web, the Content Length in the header becomes out by 1 byte.

If you modify the Content Length value in the header, it will work in Chrome, but fail in Firefox, IE & Opera who all follow the RFCs correctly.

I'm not sure which application is actually at fault, but it isn't something you can easily fix yourself.

0
On

You say Chrome keeps rendering the same image? try sending headers to tell the browser not to cache anything.

header('Pragma: no-cache');
header('cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 1999 00:00:00 GMT'); 
0
On

Adding a

ob_clean();

solved for me.

Full example:

$img = imagecreatefromjpeg('my_image.jpg');
ob_clean();
header('Content-Type: image/jpeg');
imagejpeg($img);
imagedestroy($img);