将用户输入的 CAPTCHA 值与会话中存储的预期值进行比较
我正在尝试在我正在构建的表单中实现一个简单的验证码,但我遇到了一个我自己似乎无法解决的问题。
我使用简单的代码来生成一个随机数,如下所示
$randomnr = rand(1000, 9999);
$_SESSION['randomnr2'] = md5($randomnr);
......然后使用更多代码来生成随机数的图像并将其显示在页面上。我反对这样的有效性......
if (strlen($captcha) !== ($_SESSION['randomnr2'])) {
$error['captcha'] = "CAPTCHA error. Please try again";
}
我如何根据会话randomnr2
中存储的随机数检查输入验证码输入字段的值?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定为什么您要根据此处字符串的 md5 哈希值检查字符串的长度,但假设
$captcha
是来自用户的数字,您可以这样做: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:对于
strlen()
,PHP 会自动将任何内容转换为字符串(如果可以),因此两者都会输出“2”,即使第一个是整数。要将提交的值与存储的值进行比较,就像
您需要再次将提交的值转换为 int 一样简单,因为 PHP $_GET/POST 数组中的任何内容在内部都被视为字符串。
PHP will auto-convert anything to a string (if it can) for
strlen()
, sowill 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
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.
...
通过 scriptmonkey 附加...
查看开源验证码脚本。您的实现将要求在页面上发送验证码,无论拉动页面的内容都可以看到其值,并且该人/机器人/任何内容都可以相应地填写验证字段,因此您实际上拥有零保护。这就是为什么验证码要么使用难以用脚本阅读的复杂图像,要么使用人类在上下文中比机器人更容易理解的语义问题,例如“你认为 1 和 3 的总和是多少?” === 4]。是的,带有设置字体、间距和大小的更简单的图像验证码可以通过某种像素模式字典攻击来破解。
...
attached via scriptmonkey...
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.