What Do I Need to Store in the PHP Session When User Logged In

What do I need to store in the php session when user logged in?


Terminology

  • User: A visitor.
  • Client: A particular web-capable software installed on a particular machine.

Understanding Sessions

In order to understand how to make your session secure, you must first understand how sessions work.

Let's see this piece of code:

session_start();

As soon as you call that, PHP will look for a cookie called PHPSESSID (by default). If it is not found, it will create one:

PHPSESSID=h8p6eoh3djplmnum2f696e4vq3

If it is found, it takes the value of PHPSESSID and then loads the corresponding session. That value is called a session_id.

That is the only thing the client will know. Whatever you add into the session variable stays on the server, and is never transfered to the client. That variable doesn't change if you change the content of $_SESSION. It always stays the same until you destroy it or it times out. Therefore, it is useless to try to obfuscate the contents of $_SESSION by hashing it or by other means as the client never receives or sends that information.

Then, in the case of a new session, you will set the variables:

$_SESSION['user'] = 'someuser';

The client will never see that information.


The Problem

A security issue may arise when a malicious user steals the session_id of an other user. Without some kind of check, he will then be free to impersonate that user. We need to find a way to uniquely identify the client (not the user).

One strategy (the most effective) involves checking if the IP of the client who started the session is the same as the IP of the person using the session.

if(logging_in()) {
$_SESSION['user'] = 'someuser';
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}

// The Check on subsequent load
if($_SESSION['ip'] != $_SERVER['REMOTE_ADDR']) {
die('Session MAY have been hijacked');
}

The problem with that strategy is that if a client uses a load-balancer, or (on long duration session) the user has a dynamic IP, it will trigger a false alert.

Another strategy involves checking the user-agent of the client:

if(logging_in()) {
$_SESSION['user'] = 'someuser';
$_SESSION['agent'] = $_SERVER['HTTP_USER_AGENT'];
}

// The Check on subsequent load
if($_SESSION['agent'] != $_SERVER['HTTP_USER_AGENT']) {
die('Session MAY have been hijacked');
}

The downside of that strategy is that if the client upgrades it's browser or installs an addon (some adds to the user-agent), the user-agent string will change and it will trigger a false alert.

Another strategy is to rotate the session_id on each 5 requests. That way, the session_id theoretically doesn't stay long enough to be hijacked.

if(logging_in()) {
$_SESSION['user'] = 'someuser';
$_SESSION['count'] = 5;
}

// The Check on subsequent load
if(($_SESSION['count'] -= 1) == 0) {
session_regenerate_id();
$_SESSION['count'] = 5;
}

You may combine each of these strategies as you wish, but you will also combine the downsides.

Unfortunately, no solution is fool-proof. If your session_id is compromised, you are pretty much done for. The above strategies are just stop-gap measures.

PHP - How can i keep my user logged in?

First off I would highly recommend not using the LIKE operator, use the = operator instead. Also I would recommend using parametrized quires. Also I would recommend hashing your user's passwords, salting them is a very good idea too.

Give these pages a read. There is good information here:

How can I prevent SQL injection in PHP?

Secure hash and salt for PHP passwords

crackstation.net supplies a free library for multiple languages and a good explanation.

But you need to keep track of the logged in user:

function verificarCliente($login, $password) {

$sql = "SELECT * FROM users WHERE login = '$login' AND password = '$password'";
if(($rs=$this->bd->executarSQL($sql))){
if(mysql_fetch_row($rs)==false) {
return false;
} else {
session_start();
$the_username = // grab the username from your results set
$_SESSION['username'] = $the_username;

// put other things in the session if you like
echo "<br><b> <a>Bem-Vindo <font size=2>" .mysql_result($rs,0,"login")."</font></b></a><br><br><br>";

return true;

}
}
else {
return false;
}
}

Now on other pages that require a user to be logged in

session_start();
if (!isset($_SESSION['username']) || empty($_SESSION['username'])) {
// redirect to your login page
exit();
}

$username = $_SESSION['username'];
// serve the page normally.

php keep user logged in using session, after changing page

@waterloomatt & @Isaac thanks for your time and responses! After so many hours, finally i found the code that works. If you see anything wrong, i would be happy to know!
Will i have problems with SQL Injection attacks?

login.php

<?php
session_start();

include 'db_info.php';

//connect to db
$conn = new mysqli($dbServer, $dbUser, $dbPass, $dbName)
or die($conn);

//get values
if ((isset($_POST['user'])) && (isset($_POST['user']))){
$username = $_POST['user'];
$password = $_POST['pass'];
} else {
$username = null;
$password = null;
}

//prevent mysql injection
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);

//encrypt pass
$encrypted = hash('sha256', $password);

//search
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$encrypted'";
$result = mysqli_query($conn, $sql) or die("Failed to query database ".mysqli_error($conn));

//compare
$row = mysqli_fetch_array($result);
if (($row['username'] != $username) || ($row['password'] != $encrypted)){
if ((isset($_POST['user'])) && (isset($_POST['pass']))){
$_SESSION['msg'] = 'Credentials mismatch';}
} else {
$_SESSION['id'] = $row['id'];
$_SESSION['user'] = $row['username'];
}
mysqli_close($conn);


?>

mysky.php

<?php 
include 'login.php';

if ((isset($_SESSION['id'])) && (isset($_SESSION['user'])))
{
include 'sky_auth.php';
}
else
{
include 'sky_login.php';
}

include 'footer.php';
?>

sky_login.php

<?php 
$pageTitle = 'MySky Login';
include 'header.php';
?>


<div id="cloud_box">
<div id="cloud_title">My<span>Sky</span> Login</div>

<form action="" name="form" method="POST" onsubmit="return IsEmpty();">

<div id="msg"><?php if (isset($_SESSION['msg'])){
echo $_SESSION['msg'];
unset($_SESSION);
session_destroy();} ?>
</div>

<div id="u">
<div id="user1">U</div>
<input type="text" id="user" name="user"/>
<div id="error_u"></div>
</div>

<div id="p">
<div id="pass1">P</div>
<input type="password" id="pass" name="pass"/>
<div id="error_p"></div>
</div>

<button id="btn" type="submit">Login</button>

</form>

</div>

sky_auth.php

<?php
if(!isset($_SESSION['id']))
{
header("Location: mysky.php");
die();
}
$pageTitle = sprintf('MySky - %s', $_SESSION['user']);
include 'header.php';
?>

<div id="sky_contain">

<div id="logout"><a href="logout.php">Logout</a></div>

</div>

</div>

PHP Login, Store Session Variables

Let me bring you up to speed.

Call the function session_start(); in the beginning of your script (so it's executed every page call).

This makes sessions active/work for that page automagicly.

From that point on you can simply use the $_SESSION array to set values.

e.g.

$_SESSION['hello'] = 'world';

The next time the page loads (other request), this wil work/happen:

echo $_SESSION['hello'];  //Echo's 'world'

To simply destroy one variable, unset that one:

unset($_SESSION['hello']);

To destroy the whole session (and alle the variables in it):

session_destroy();

This is all there is about the sessions basics.

Using sessions & session variables in a PHP Login Script

Hope this helps :)

begins the session, you need to say this at the top of a page or before you call session code

 session_start(); 

put a user id in the session to track who is logged in

 $_SESSION['user'] = $user_id;

Check if someone is logged in

 if (isset($_SESSION['user'])) {
// logged in
} else {
// not logged in
}

Find the logged in user ID

$_SESSION['user']

So on your page

 <?php
session_start();


if (isset($_SESSION['user'])) {
?>
logged in HTML and code here
<?php

} else {
?>
Not logged in HTML and code here
<?php
}

What data should I store in a PHP session?

You should only keep temporary data in sessions that tracks that current user. Anything else should stay hidden in the database until it's needed.

PHP how to keep user logged until they log out?

You can use a cookie for this. When the user logging in for the first time, set a cookie for maybe 10 years. Then, when the user navigates the pages, update/reset the cookie to a further 10 years.

setcookie(
"CookieName",
"CookieValue",
time() + (10 * 365 * 24 * 60 * 60)
);

Setting a Cookie in PHP

And when the user comes back to the site after some time, check if the cookie is available. If available, you can log them in automatically, if not, redirect to the login page.

if(isset($_COOKIE['CookieName'])){
$cookie = $_COOKIE['CookieName'];
}
else{
// No Cookie found - Redirect to Login
}

You can use two cookies for user name and password(encrypted).



Related Topics



Leave a reply



Submit