views:

443

answers:

2

i m working on a website..... and wants to create user login and their session..... what is the safest way to check their session exist or not( like cookie or session variable check)..... or any better idea then using sessions in php

+1  A: 

Here's some tutorials on Session Safety

Ólafur Waage
+2  A: 

session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).

http://de.php.net/manual/en/function.session-id.php

but that just tells you if a session is active or not.

most of the time, i just call session_start(); at the beginning of every script (even if the user's not logged in). on login, i set $_SESSION['user'] with the userid or an user object. on logout, i just unset($_SESSION['user']);. by checking empty($_SESSION['user']) i can check if someone's still logged in or not. don't do this if you're storing user-dependant information elsewhere in your session, otherwise the next guy logging in may get info he's not supposed to see (in this case use session_destroy();).

but safety? just deactivate session-id propagation by GET/POST url rewrites (cookies only), so they don't end up in URLs that can be cached or distributed to others (in this case, session hijacking would be possible). you can do that by setting session.use_only_cookies in the php.ini.

there may be additional safety issues if you're hosting on an untrusted and/or misconfigured shared server - it could lead to other people on the same machine reading your session data. in this case you could store your session data in a database by rewriting your session handler. just search for session handler mysql on the intertubes, i'm sure there are enough ready-to-go solutions. and don't store sensitive information like passwords in the session, better do a query everytime you need to compare it.

other than that ... use ssl/https for login and user management, so no plaintext passwords are transfered. store only pw-hashes with salt in the database. don't let anybody see the passwords (meaning: never print them to html or emails). don't use auto_increment values for ids the user can see (and therefore, guess). ok, that's already out of the questions scope.

Schnalle
'and don't store sensitive information like passwords in the session, better do a query everytime you need to compare it.' - well, i think is faster to store a one-way crypted version of the password(md5+hash), and check it instead to remake the query to the db again and again
DaNieL
true, but normally you don't need to check the password on every pageview, only on #1: logging in and #2: changing it (if you ask the user to provide the current pw to set a new one). for #1 you HAVE to query the database, and #2 doesn't happen very often, so the additional overhead is negligible.
Schnalle