4

使用我的 sql 表中的 user_id 作为会话 id 是否不安全?这通常是 php 开发人员所做的吗?


(来源:sockface.com

我也尝试过无数次将会话 ID 存储为用户 ID

include('profile/core/init_inc.php');    
$_SESSION['uid'] = $user_id;
header("Location: profile/edit_profile.php");

在我的 init_inc

function fetch_user_info($uid){
$uid = (int)$uid;

$sql = "SELECT
            `user_id` AS `id`,
            `username`,
            `user_firstname` AS `firstname`,
            `user_lastname` AS `lastname`,
            `user_about` AS `about`,
            `user_email` AS `email`
        FROM `users`
        WHERE `user_id` = {$uid}";

$result = mysql_query($sql);        
return mysql_fetch_assoc($result);

如果我有 $_SESSION['uid'] = 90; 登录后它将在此处显示 test@test.ca 信息

所以我的问题是,将会话 ID 存储为 user_id 是否安全,当我尝试这样做时,为什么它不起作用?

4

1 回答 1

2

A couple things:

1.) A session ID should not be a constant value for a particular user. That is a security violation. The session ID should change every once in a while. Ideally, it should be a random value.

2.) It doesn't look like you are setting the session ID. You are setting the session variable called "uid".

3.) Did you ever call session_start()?


Despite the fact that I really would not recommend setting a session ID to a constant value, you can set the ID for a session using the session_id() function:

$session_id = "some_random_value";
session_id($session_id);

But like I said, this should not be the user's ID. You can store the user's ID as session information, and check that when the user loads a page to see if they are logged in.

if (isset($_SESSION["user_id"]))
{
    //user is logged in
    $user_id = $_SESSION["user_id"];
}
else
{
    //make user log in
    $user_id = result_of_login();
    $_SESSION["user_id"] = $user_id;
}

More information on PHP sessions in the session documentation.

于 2012-10-13T04:41:36.530 回答