简体   繁体   中英

The correct way to use sessions?

I'm fairly new to PHP.

I've made a login system for my website and I'm wondering if I'm going about this the right way. On my login.php that processes the login request I have created session variables to use on my site. I am wondering if this is the most efficient/secure way to store the users data.

This method seems to work quite well for me. But let's say I require data from another table not including in my users table. How would I go about getting that info and storing it into a session? Does this leave my users vulnerable due to the browser having all this information? or am I getting a completely wrong understanding of sessions.

<?php
/* User login process, checks if user exists and password is correct */

// Escape email to protect against SQL injections
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM users WHERE email='$email'");

if ($result->num_rows == 0) { // User doesn't exist
    $_SESSION['message'] = "User with that email doesn't exist!";
    header("location: error.php");
} else { // User exists
    $user = $result->fetch_assoc();

    if ( password_verify($_POST['password'], $user['password']) ) {

        $_SESSION['email'] = $user['email'];
        $_SESSION['user_name'] = $user['user_name'];
        $_SESSION['active'] = $user['active'];
        $_SESSION['paid'] = $user['paid'];
        $_SESSION['bitaddress'] = $user['bitaddress'];
        $_SESSION['id'] = $user['id'];
        $_SESSION['firstName'] = $user['firstName'];
        $_SESSION['lastName'] = $user['lastName'];

        // This is how we'll know the user is logged in
        $_SESSION['logged_in'] = true;

        header("location: checksum.php");
    } else {
        $_SESSION['message'] = "You have entered wrong password, try again!";
        header("location: error.php");
    }
}

your should create a methods for sessions like:

function session_start(){
  session_start()
}
function session_create($key,$value){
  return   $_SESSION[$key] = $value;
}
function session_destroy(){
  session_destroy();
}

As long as you use different keys, you can store data from many tables(or any other values).

Sessions are stored in the server side, so your browser does not have this information. There are still vulnerabilities though, see session hijack https://www.owasp.org/index.php/Session_hijacking_attack .

In general, you use the sessions well.

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