How to use PHP Cookie-based Sessions

By

Learn how to use cookie-based sessions in PHP with session_start, store data server-side in $_SESSION, and clear it with session_unset.

~~~

To use cookie-based sessions in PHP you call session_start() at the top of your script, then read and write data through the $_SESSION array. PHP handles the cookie part for you.

Why do we need sessions?

HTTP is stateless. Every request starts from zero, and the server has no idea if two requests come from the same visitor.

Cookies help, but storing data directly in a cookie has problems. The user can see it, the user can change it, and cookies have a small size limit.

Sessions solve this. The cookie only carries a random ID. The actual data lives on the server.

Starting a session

PHP offers us a very easy way to create a cookie-based session using session_start().

Try adding

<?php
session_start();
?>

in a PHP file, and load it in the browser.

You will see a new cookie named by default PHPSESSID with a value assigned.

That’s the session ID. This will be sent for every new request and PHP will use that to identify the session.

Browser developer tools showing PHPSESSID cookie created by session_start function

Storing data in the session

Similarly to how we used cookies we can now use $_SESSION to store the information sent by the user, but this time it’s not stored client-side.

Only the session ID is.

The data is stored server-side by PHP.

<?php
session_start();

if (isset($_POST['name'])) {
  $_SESSION['name'] = $_POST['name'];
}
if (isset($_POST['name'])) {
  echo '<p>Hello ' . $_POST['name'];
} else {
  if (isset($_SESSION['name'])) {
    echo '<p>Hello ' . $_SESSION['name'];
  }
}
?>

<form method="POST">
  <input type="text" name="name" />
  <input type="submit" />
</form>

Submit the form once, then reload the page. The greeting is still there, even though no form data was sent. PHP looked up the session by its ID and found the name you stored.

Web page showing Hello test message with PHPSESSID cookie visible in browser developer tools

This works for simple use cases, of course for intensive data you will need a database. Sessions are great for small things: the logged-in user’s ID, a flash message, a shopping cart.

Watch out for the “headers already sent” error

Be careful where you call session_start(). It sets a cookie, and cookies travel in HTTP headers. Headers must go out before any output.

If your file prints anything first, even a single blank line before the <?php tag, you get a warning like “session_start(): Session cannot be started after headers have already been sent”.

The fix: make session_start() the very first thing in the file, before any HTML or whitespace.

Clearing the session

To clear the session data you can call session_unset(). This empties $_SESSION but keeps the session alive.

To destroy the session entirely, call session_destroy().

To clear the session cookie use:

setcookie(session_name(), '');

This is what you’d wire up to a logout button: destroy the data, then remove the cookie.

Tagged: PHP · All topics
~~~

Related posts about php: