Skip to content
Advertisement

setting session id variable from sql database; is this safe?

Is it unsafe to use the user_id in my sql table as the session id? is this normally what php developers do?


(source: sockface.com)

Also I’ve tried countless times to store the session id as the user id

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

in my 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);

If i have $_SESSION[‘uid’] = 90; it will display test@test.ca info here after you log on

so my question is, is it safe to store the session id as the user_id, and how come when i try to do it, why isn’t it working?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement