开发者

PHP "Session_regenerate_id" and Authentication of users

开发者 https://www.devze.com 2023-01-23 14:53 出处:网络
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 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开发者_如何学Python 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消