php Captcha返回旧值并检查旧值

时间:2014-09-04 10:44:56

标签: php html css captcha spam-prevention

我正在使用此脚本:https://github.com/claviska/simple-php-captcha

在php中制作验证码。

我有这个代码:

session_start();
include_once 'simple-php-captcha.php';
$_SESSION = array();
$_SESSION['captcha'] = simple_php_captcha();
$code = $_SESSION['captcha']['code'];
if (isset($_POST['username'])&&isset($_POST['password'])) {
    if (!empty($_POST['username']) && !empty($_POST['password'])) {
                    $username = $_POST['username'];
                    $password = $_POST['password'];
                        if (isset($_POST['captcha'])&&!empty($_POST['captcha'])) {
                            $captcha = $_POST['captcha'];
                            if ($captcha == $code) {
                                echo "Login";
                            } else {
                                $errors[] = "Capcha is Not True.";
                            }
                        } else {
                            $errors[] = "Enter capcha.";
                        }
        } else {
                    $errors[] = "Enter all.";
                }
}

和HTML表单:

<form accept="" method="POST">
username: <input type="text" name="username">
password: <input type="password" name="password">
captcha:  <input type="text" name="captcha">
<img src="<?php echo $_SESSION['captcha']['image_src']; ?>">
<input type="submit" class="Button" value="submit">
</form>

BUT

问题是每次我输入验证码并提交表格时,都会生成较新的验证码,表格总是返回 NOT TRUE CAPTCHA pm。

例如我打开页面,例如验证码是:52111, (我输入正确)然后我提交,然后我看到验证码不正确的错误,因为生成的较新的验证码是另一个像:48852。

我的意思是每次页面生成一个新的,我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

在检查表单之前,您应该保存旧的验证码值:

session_start();
if (!isset($_SESSION['captcha']) {
    $_SESSION['captcha'] = simple_php_captcha();
}
$code = $_SESSION['captcha']['code'];

include_once 'simple-php-captcha.php';
if (isset($_POST['username'])&&isset($_POST['password'])) {
    if (!empty($_POST['username']) && !empty($_POST['password'])) {
                $username = $_POST['username'];
                $password = $_POST['password'];
                    if (isset($_POST['captcha'])&&!empty($_POST['captcha'])) {
                        $captcha = $_POST['captcha'];
                        if ($captcha == $code) {
                            echo "Login";
                        } else {
                            $errors[] = "Capcha is Not True.";
                        }
                        unlink($_SESSION['captcha'])
                    } else {
                        $errors[] = "Enter capcha.";
                    }
    } else {
                $errors[] = "Enter all.";
    }
}

答案 1 :(得分:0)

在JS中添加一些带有当前日期的查询字符串,以便从浏览器中删除图像:

$('img').prop('src',+"<?php echo $_SESSION['captcha']['image_src']; ?>?_="+new Date().valueOf())