PHP令牌没有给出正确的错误

时间:2015-01-23 11:06:44

标签: php session token

我的令牌表单出现了轻微问题。出于某种原因,它不会检查后期令牌是否等于会话令牌,因此我不确定它是否正常工作。 我打印了POST和SESSION令牌以检查它们是否匹配,他们这样做了。所以目前我没有想法。

<?php

session_start();
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
$_SESSION['token_time'] = time();

include_once('includes/connection.php');

if (isset($_SESSION['logged_in'])) {

?>
//loggedin

<?php
} else {
    if (isset($_POST['username'], $_POST['password'])) {
        $username = $_POST['username'];
        $password = md5($_POST['password']);
        $token2 = $_POST['token'];

        if ($token2 != $token) {
            $error  ='Error';
            echo $token2;
        }

        if (empty($username) or empty($password)) {
            $error = 'Insert data!';

        } else {
            $query = $pdo->prepare("SELECT * FROM users WHERE user_name = ? AND user_pass = ?");

            $query->bindValue(1, $username);
            $query->bindValue(2, $password);

            $query->execute();

            $num = $query->rowCount();

            if ($num == 1) {
                $_SESSION['logged_in'] = true;
                header('Location: index.php');
                exit();
            } else {
                $error = 'Wrong data';
            }
        }
    } 

            <?php if (isset($error)) { ?>
                <small style="color:#aa0000;"><?php echo $error; ?>
                <br /><br />
            <?php } ?>

            <form action="index.php" method="post" autocomplete="off">
                <input type="text" name="username" placeholder="Username" />
                <input type="password" name="password" placeholder="Password" />
                <input type="text" name="token" value="<?php echo $token; ?>" />
                <input type="submit" value="Sisene" />
            </form>

2 个答案:

答案 0 :(得分:1)

您正在为每个请求重新定义令牌:

session_start();
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;

你能做的是:

session_start();
if(empty($_SESSION['token'])) {
    $token = md5(uniqid(rand(), TRUE));
    $_SESSION['token'] = $token;
}
else {
    $token = $_SESSION['token'];
}

答案 1 :(得分:0)

提交表单后,系统会生成新的$_SESSION['token'] = $token;,因此if ($token2 != $token)始终是错误的。

您可以在生成新的$_SESSION['token'] = $token;之前检查是否已设置{{1}}。