safest way to create sessions in php

I'm working on a website and want to create user login and session. What is the safest way to check if session exists or not (like cookie or session variable check), or any better idea then using sessions in php?


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.


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)
  • 链接地址: http://www.djcxy.com/p/64460.html

    上一篇: C ++中的具体模板友谊

    下一篇: 最安全的方式来创建会话在PHP中