Comparing user-input CAPTCHA value against expected value stored in session
I'm trying to implement a simple captcha into a form I'm building but I've run up against an issue I can't seem to sort out by myself.
I'm using simple code to generate a random number like so ....
$randomnr = rand(1000, 9999);
$_SESSION['randomnr2'] = md5($randomnr);
.... and then some more code to generate an image of the random number and display it on the page. I'm against it for validity like this ....
if (strlen($captcha) !== ($_SESSION['randomnr2开发者_高级运维'])) {
$error['captcha'] = "CAPTCHA error. Please try again";
}
How do I go about checking the value that's been input into the captcha input field against the random number that's stored in the session randomnr2
?
I'm not sure why you are checking the length of the string against an md5 hash of the string here, but assuming $captcha
is the number from the user, you can just do this:
if(md5($captcha) !== $_SESSION['randomnr2']) {
$error['captcha'] = "CAPTCHA error. Please try again";
}
PHP will auto-convert anything to a string (if it can) for strlen()
, so
echo strlen(42);
echo strlen('42');
will both output '2', even though the first one's an integer. To compare the submitted value to the store value, it's as simple as
if ($_SESSION['randomnr2'] === (int)$captcha) {
... it matched ...
}
You'll want to cast the submitted value to an int again, as anything in the PHP $_GET/POST arrays is internally treated as a string.
<div id='captcha_to_show' style='border:1px solid silver;'>gobldeygook</div>
<input name='captcha' id='captcha'>
...
attached via scriptmonkey...
$('document').ready(function(){
$('#captcha').val($('#captcha_to_show').html());
});
look into a open-source captcha script. your implementation is going to require sending that captcha across the page in a way that it's value can be seen by whatever is pulling the page, and that person/bot/whatever can fill in the validating field accordingly, so you actually have zero protection. that is why captchas either use convoluted images that are hard to impossible to read with a script, or semantic questions better understood by humans in context than bots, such as ['What would you say the sum of one and 3 are?' === 4]. and yes, the more simple image captcha's with the set fonts, spacing and size can be hacked with a sort of pixel-pattern dictionary attack.
精彩评论