简体   繁体   中英

PHP “Session_regenerate_id” and Authentication of users

I am creating a login-function on my website, and I am thinking about regenerating the session ID on every page to make things more secure.

I have read PHP:s information about regenerate_id but the posts on the PHP page are quite different from the information they provide about session_regenerate_id.

Could somebody explain these two questions:

  • Do I need to copy the old session data into the newly generated one, or is this done automatically? Code examples are very much appreciated...

  • How do I check to see if a user is already logged in? What should I store in the session variable, and how? Code examples are very much appreciated...

Thanks

Calling session_regenerate_id() on every page may be a little bit of overkill, depending on your setup. The function is used to prevent session hijacking and should be used whenever a user elevates their level of privilege (such as logging in). Usually you would switch to a https connection once a user is logged in, meaning you only need to call session_regenerate_id() once as the new cookie would be tranmitted over a secure connection and wouldn't be able to be eavesdropped. However, if you don't have a SSL certificate on your server regenerating the session cookie on every page could be a good option.

When you call session_regenerate_id() you don't need to copy session data. This is all taken care of for you by PHP. Basically a new session token and cookie are created, session data is copied in the session store to be associated with the new token, and if you pass true as the single argument to the function the old session data file on disk is deleted.

What you store in the session to indicate if a user is logged in is up to you. I often just store a simple boolean value to indicate if they're logged in, along with other values holding usernames, name, etc. Then checking if someone is logged in is as simple as this:

<?php
    if ($_SESSION['logged_in']){
        //User logged in
    } else {
       //User not logged in
    }
?>

HTH.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM