W1234XY
W1234XY

Reputation: 3

PHP token not giving a correct error

I've got a slight problem with my token form. For some reason it wont check if post token equals to session token so I'm not sure if it's working or not. I've printed POST and SESSION tokens to check if they match, they do. So currently I'm out of ideas.

<?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>

Upvotes: 0

Views: 188

Answers (2)

Alex
Alex

Reputation: 6037

After submitting the form a new $_SESSION['token'] = $token; is generated, so if ($token2 != $token) is always wrong.

You could check if $_SESSION['token'] = $token; is set before generating a new one .

Upvotes: 0

Laurent W.
Laurent W.

Reputation: 3783

You are redefining the token on each request :

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

What you could do is :

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

Upvotes: 1

Related Questions