Although it works, @Pullo ; 's method is quite easy to reverse engineer, since the solution to cracking the 'captcha' is right there in the javascript.
So if somebody really wanted they could just look at that code and work around it in a matter of minutes.
Better would be to store the required answer server side in a session and then if you want to validate with javascript do a AJAX request to the server to check if the entered answer is correct, which you can easily do with the bassistance validator using the 'remote' method.
This keeps asking the same question as long as it isn't answered correctly. Once answered correctly it will generate a new captcha, thus lowering the chance of replay attacks.
form.php
PHP Code:
<?php
session_start();
if (!isset($_SESSION['num1']) && !isset($_SESSION['num2'])) {
$_SESSION['num1'] = rand(1,5);
$_SESSION['num2'] = rand(1,5);
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Spam filter example 2</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.js"></script>
</head>
<body>
<form action="post.php" method="post" id="myForm">
<div>
<label for="spam_question">What is <?php echo $_SESSION['num1'] ?> + <?php echo $_SESSION['num2'] ?>?</label>
<input type="text" id="spam_question" name="spam_question">
</div>
<input type="submit">
</form>
<script>
$("#myForm").validate({
rules: {
spam_question: {
required: true,
remote: {
url: "validate-captcha.php",
type: "post",
}
}
}
});
</script>
</body>
</html>
post.php
PHP Code:
<?php
session_start();
if (!isset($_SESSION['num1']) || !isset($_SESSION['num2'])) {
exit('Incorrect answer');
}
$sum = (int)$_SESSION['num1'] + (int)$_SESSION['num2'];
if (isset($_POST['spam_question']) && (int)$_POST['spam_question'] === $sum) {
unset($_SESSION['num1'], $_SESSION['num2']);
exit('Correct answer!');
}
exit('Incorrect answer');
validate-captcha.php
PHP Code:
<?php
session_start();
if (!isset($_SESSION['num1']) || !isset($_SESSION['num2'])) {
exit('"Incorrect answer."');
}
$sum = (int)$_SESSION['num1'] + (int)$_SESSION['num2'];
if (isset($_POST['spam_question']) && (int)$_POST['spam_question'] === $sum) {
exit('true');
}
exit('"Incorrect answer."');
Bookmarks