8

New to php Sessions here. My stored user data is pretty minor and not very sensitive but of course I still want a secure site. I have stored their password hash in my db with salt.

Do I need to validate a user on every page of my site using their password, or is that overkill? In other words, if they have successfully "logged in" and I have stored their username in a php session is that good enough for them to roam around, with the site knowing who they are?

I ask because it seems like storing a users password in a session is probably not the best idea. Is that true?

6 Answers 6

9

You don't need to authenticate on every request, but you do need to authorize on every request.

Authentication is where you validate the user's username / password against the database. Once they have successfully authenticated, you only need to store their user ID (or username) in the session.

On every subsequent request, check to make sure that the current session is authorized to view the requested content. In your case, you probably just need to make sure that there is a valid user ID in the session... you don't have to do anything with the database.

You may use a function similar to the following to authorize on every request:

function isAuthorized() {
    return isset($_SESSION['user_id']) && ($_SESSION['user_id'] != 0);
}

You can make this even more secure by managing your own session data in a database, and then you don't have to place much faith in cookies, which can be traded/stolen/etc by (malicious) users. But that's usually overkill for most web apps.

5

Don't store the password. Instead, store an authentication token that you can check for existence of in a separate table.

2

I wouldn't store the password in the session, you can just store that they have logged in in the session.

$_SESSION['uerlogged'] = $mytoken;

Then each page load check to see if $_SESSION['userlogged'] is set.

You may also want to consider adding in precautions for session hi-jacking Take a look at - PHP: Preventing Session Hijacking with token stored as a cookie?

0
1

It shouldn't really be necessary to store a password in a session. You should have status flags to show whether or not they're currently authenticated along with some sort of object that defines who the user is and information about them.

0

Storing the password in the session isn't any different than storing the username in the session once the user logged in, so don't store the password.

It will just work as the stored username, which is enough (even a flag will do).

0

Users can't modify sessions, you can store only the username there and trust that it will always be correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.