Basicly, if you show your captcha image captcha_code_file.php, you generate a code to display.
Save this Code in the User Session. If your Form is sended, you check, if the captcha code is in the session.
The rand=1846368456 parameter, is only to ensure, that you see the latest generated picture, and not some cached one.
How to check the code from JS?
You can provide an checkCaptcha.php, which basicly do the lookup in the session, and echo true or false. Before sending your Form, you can do an Ajax call to it.
checkCaptcha.php?code=foobar
$code = isset($_GET['code']) ? $_GET['code'] : '';
$sessionCode = isset($_SESSION['captchacode']) : $_SESSION['captchacode'] : '';
if (empty($code) || $code !== $sessionCode) {
die('FALSE');
}
die ('TRUE');
Ajax:
var captchacode = 'foobar'; //Read from Input
$.get("checkCaptcha.php?code=" + captchacode, function( data ) {
if (data == 'FALSE') {
alert('Error with Captcha');
}
});
On Form submit, you should clear the "used" captcha code.
Whats about Security?
We always check Captcha Code on Server side. This ajax is only for User Experience.
I don't think this solution provides a security hole.
It is more easy to do single Post:
$success = false
while(!$sucess) {
$code = tryReadCode();
$result = attackPageViaPost($code);
$success = str_pos('Congrats, you successfuly entered the captcha', $result) !== false;
}
then
$success = false
while(!$sucess) {
$code = tryReadCode();
$success = getAjaxResult($code);
}
attackPageViaPost($code)