PHP and JavaScript: Reload captcha image

4.7k views Asked by At

I've made my own captcha class in PHP, just to learn. It's ok, working as I want. I've tried to add a "refresh image" button but I don't know how do I do that.

form code:

<p><img src="img.php" alt="Captcha!" /></p>

img.php code:

<?php
require_once 'captcha.class.php';
$captcha = Captcha::instance(10);
echo $captcha;
?>

__toString method:

public function __toString()
{
    ob_start();
    header('Content-Type: image/jpeg');
    imagejpeg($this->drawImage(), null, 100);
    return ob_get_flush();
}

These code will output the captcha. How could I refresh this image? Something in AJAX would be great! Thank you.

3

There are 3 answers

0
Connell On BEST ANSWER

How are you checking the captcha is correct when the form is completed? Session variable?

If it is a single session variable, you could just refresh the image using plain javascript. Adding a random query string to the end of the image url would avoid any caching issues.

0
Don On

Could you have the reload make an AJAX call to a page that creates a new captcha, the return the newly created result into a DIV?

6
Poelinca Dorin On
<html>
<head>
<script type="text/javascript">
    function reload()
    {
        var img = new Image();
        img.src = 'img.php';
        var x = document.getElementById('captcha');
        x.src = img.src;
    }
</script>
</head>
<body>
<a href="javascript: reload()" >Reload</a>
<img src="img.php" alt="Captcha!" id="captcha" />
</body>
</html>

Maybe a plain x.src = 'img.php' would do the trick but just to be shure it get's a new request i've made it using another image ( it allso gives you a bit more to search/learn ) .