Search code examples
phpjavascriptajaxcaptchapartial-page-refresh

PHP and JavaScript: Reload captcha image


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.


Solution

  • 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.