reet
reet

Reputation: 51

how to use session ids for authentication purpose

I am using just session variables $_SESSION['user_id'] and $_SESSION['passwd'] to store the id and password of user once when he logs in.

I am just checking these two variables with database each time the user moves to a new php page for authentication. Actually I didnt know about session_id() .

I dont think what i am doing for authentication is the right way. I feel that there is something to be done with session_id for security stuff.

and one more doubt- can these session variables be easily hacked when I use the session variables by the way i mentioned

What should I do?

Upvotes: 5

Views: 4529

Answers (5)

Rui
Rui

Reputation: 516

You don't need to check everytime the user moves to a new php. Once user authenticates, store the session_id in $_SESSION['session_id'] for example. After that all you need to do is check if $_SESSION['session_id'] is set. If it is, it means user is "logged in".

Hope it helps.

Upvotes: -1

Demento
Demento

Reputation: 4307

An attacker cannot easily change or read your $_SESSION variables, as long as there is no other vulnerability present, but it is general bad practice to store a password any longer than necessary on the server for several reasons.

It is sufficient to check the password once when the user logs in. Afterwards you only need to store the authenticated user_id in the session. You have to know who the session belongs to, to grant the necessary permissions to this specific user. But you do already know that the user submitted the correct password, otherwise you wouldn't have stored his user_id in the session in the first place.

Upvotes: 4

Your Common Sense
Your Common Sense

Reputation: 158007

Sure.
$_SESSION['user_id'] is only variable you need.

if (empty($_SESSION['user_id'])) {
   die("access denied");
}

to check if user is authenticated.

Upvotes: 0

Jon Skarpeteig
Jon Skarpeteig

Reputation: 4128

You should only authenticate against the database once, then store the result in the $_SESSION var. Example:

if ($user_and_pass_ok) {
  $_SESSION['user_logged_in'] = true;
}

Upvotes: 0

Richard Tuin
Richard Tuin

Reputation: 4562

For basic authentication your approach of storing the user id is fine. However, you don't need to store the password while the user is authenticated.

Upvotes: 1

Related Questions