How to Use Sessions Correctly in PHP – Best Practices

databasePHP

I am making a website that requires logins, and would like to know what a good approach is.
Right now, I am thinking of the following:

  1. User sends username and password to server, where it is validated.
  2. If its valid, then session_start(); is called, and session_id() is stored in my database, which will be used as an access token for the rest of data fetching.
  3. If user logs out, that session_id() will be destroyed in the database.

I would like to know how to delete the session_ids() , if the user DIDNT log out, and just closed the browser.

I would like to know how popular websites like facebook handle sessions.

Best Answer

You're in the right neighborhood.

Most PHP applications will have active sessions for all page views, regardless of whether a user is logged in. It would essentially do a session start() at the beginning of the script, and a save() at the end. That session would exist for the entire visit to the site, or longer, depending on how you have PHP set to expire cookies.

When a user submits a login form and successfully logs in, you can then store the user information as a session variable. For example, at the most basic, you can store the user id associated with the session:

$_SESSION['user_id'] = 1234;

When the session is saved, that value is stored with the session. Session variables are not sent to the client - they are stored on the web server (where exactly it is stored is configurable, but ideally in a database).

Now, on the next page load, you can check the value of $_SESSION['user_id'] to get the user id of the logged in user, if any. This is because when the session loads at the top of the script, it has access to the session variables you assigned on other pages in that session.

When a user logs out, you set the $_SESSION['user_id'] back to 0. On the next page load, the user is no longer associated with that session.

If you want the user to get logged out when the browser is closed, you need to set the cookie lifetime to 0. If you want the session to persist, you want to set the cookie lifetime to the maximum number of seconds you want the session to exist (for example, 60 * 60 * 24 * 30 would be 30 days).

This is just a conceptual overview. There's some security issues involved with sessions, so make sure you learn about them as well before you make a site live.

Related Topic