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
Here's some tutorials on Session Safety
- PHP Security Guide: Sessions
- Notes on PHP Session Security
- PHP Session Security - php|works 2004 (old but still interesting)
- PHP Session Security (PDF)
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).
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.