9

The session variable changes the value when the form is submitted.

 3 years ago
source link: https://www.codesd.com/item/the-session-variable-changes-the-value-when-the-form-is-submitted.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

The session variable changes the value when the form is submitted.

advertisements

I am trying to add CSRF tokens to my forms. The problem is when I add it in the file I echo out the session token and it matches the token in the input named 'token'. But when I submit the page and use Token::check it returns false and if I echo out the token value from the input and the session again I see that the session value has changed but the input value has stayed the same.

<?php
class Token{
public static function generate(){
    return $_SESSION['token'] =    base64_encode(openssl_random_pseudo_bytes(32));
}

public static function check($token){
    if(isset($_SESSION['token']) && $token == $_SESSION['token']){
        unset($_SESSION['token']);
        return true;
    }else{
        return false;
    }
}
}
?>

Here is the php to control the form.

$token = $_POST['token'];
if(Token::check($token)){ //Continue with more code }

Below is a the part of the form that deals with the tokens:

<input type="hidden" name="user_id_update" value="<?php echo $user_info[0][0]->id; ?>"/>
                            <input type="hidden" name="time_update" value="<?php echo $time; ?>"/>
                            <input type="hidden" name="token" value="<?php echo Token::generate(); ?>"
                            <hr />

                            <div class="form-group">
                                <input type="submit" id="submit_update" value="Update" class="btn btn-success"/>
                            </div>

If anybody can shed some light on this I'd really appreciate it as I've been searching online for hours now and can't find an answer. Thanks.


After some digging through the code. I found that the order that these files were added into the website meant that the code to generate the token was above the controllers for the form. As such when the form was posted it created a new session variable each time and therefore the posted data was not the same as the data stored in the session variable. Changing around the order in which these files were included solved the problem. Hope this can help someone out in the future.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK