Hylaze
Hylaze

Reputation: 31

PHP session variable does not survive

Pretty simple setup: When the page is loading, a random session token is generated and saved in $_SESSION["token"]. A Form contains this token in a hidden input field. No problems until this point. I submit the form to the very same page (action="") and then I try to check if the $_SESSION["token"] is equal to the token that has been sent via POST. A variable is changed accordingly, and then I generate a new session token that replaces the old $_SESSION["token"] before the page loads again.

Problem is: The $_SESSION["token"] is changed again the moment the page is called (Before I can compare both SESSION and POST tokens) Therefore, both tokens never match. And I can't figure out WHY it changes. It's not the lines of code I wrote, because these are executed aswell, replacing the random token of unknown origin once again, before the page loads.

INDEX:

<?php
session_start();
date_default_timezone_set("Europe/Berlin");

$BASE_URL = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

$form_valid = false;


if (isset($_POST["token"]) && isset($_SESSION["token"])) {
    if ($_POST["token"] == $_SESSION["token"]) {
        $form_valid = true;
    }
}

//Set (new) session token
$token = bin2hex(random_bytes(10));
$_SESSION["token"] = $token;

//Load actual page
include ("/backend/admin.php");
?>

INCLUDED PAGE:

 <?php echo "FORM VALID:"; var_dump($form_valid); ?> 
 <?php if (!isset($_SESSION["admin"]) || !$_SESSION["admin"]) { ?>

    <form id="verify" method="POST" action="">
        <label>Password</label>
        <input type="password" name="access">
        <input type="hidden" name="token" value="<?= $_SESSION['token'] ?>">
        <input type="submit" value="Senden">
    </form>

<?php } else { ?>

    ...

<?php } ?>

any help is appreciated. thank you.

Upvotes: 1

Views: 149

Answers (1)

Maaz Rehman
Maaz Rehman

Reputation: 704

There was a problem in your logic, session token updates every time regardless the form is submitted is not,

$token = bin2hex(random_bytes(10));
$_SESSION["token"] = $token

Try this,

 <?php
    session_start();
    date_default_timezone_set("Europe/Berlin");

    $BASE_URL = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

    $form_valid = false;


if(empty($_SESSION["token"] )){
 $_SESSION["token"]= bin2hex(random_bytes(10));
}

    if (isset($_POST["token"]) && isset($_SESSION["token"]))
 {
        if ($_POST["token"] == $_SESSION["token"]) {
            $form_valid = true;
            unset($_SESSION["token"]);
        }
    }





    include ("/backend/admin.php");
    ?>

Upvotes: 1

Related Questions