John Mwaniki /   04 Apr 2023

[Explained] The difference between PHP sessions and cookies

When building web applications, developers often need to store data between different requests made by a user. There are two common ways to do this: using PHP sessions or cookies.

Although both methods are used for storing data between requests, there are significant differences between them. In this article, we'll explore the difference between PHP sessions and cookies.

What are PHP sessions?

A PHP session is a mechanism that allows a web server to temporarily store information about a user's activity on a website. This information is accessible across multiple pages visited or requests made by the same user.

When a session is started, a temporary file is created on the server where the session variables and their values are to be stored. Also, a unique session ID (PHPSESSID) is generated, sent to the user's browser, and stored in a cookie.

The browser then sends the session ID back to the server with each subsequent request so that the server can identify the user. The server then uses this ID to retrieve session data, add new data to the session, update it, or terminate it.

The session can be used to store any information about the user, such as their personal details (eg name, username, email address, etc) and preferences among others.

PHP sessions are an integral part of web development with a lot of applications, some of which include user authentication, managing user preferences, and creating and managing shopping carts on eCommerce websites.

Session data is stored on the server, which means that it cannot be directly accessed by the user. This makes sessions more secure than storing the data on the user's computer, which can be read and modified by the user.

Creating a PHP Session

Sessions in PHP are typically started at the beginning of a script using the session_start() function. This function creates a new session or resumes an existing session if one already exists.

Once a session is started, you can store data in it using the $_SESSION superglobal array. This array is used to store key-value pairs, where the keys are the names of the variables you want to store, and the values are the information of those variables.

For example, to store the user's name in the session, you can use the following code:

<?php
session_start();
$_SESSION['name'] = 'John Doe';
?>

This code creates a new session (or resumes an existing one) and stores the value "John Doe" under the key "name" of the $_SESSION array.

Accessing Session Data

This data will be available to other scripts/pages that are part of the same session.

For example, you can create a new PHP page on the same website and use the following code to retrieve and display the user's name:

<?php
session_start();
echo 'Hi '.$_SESSION['name'].'! Great to see you again.';
?>

Output:
Hi John Doe! Great to see you again.

If you create a session array with different key(s), simply use the appropriate key to access the $_SESSION array.

You can access the session ID using the PHP session_id() function.

Updating Session Data

To update the value of a session variable, just overwrite it by assigning it a new value.

Example

<?php
$_SESSION['name'] = 'Peter Griffin';
?>

This code changes the value of the session array key "name" from "John Doe" to "Peter Griffin".

It's important to note that sessions have a limited lifespan. By default, a session last until the user closes the browser or after 24 mins of inactivity.

Related:
[Solved]: PHP sessions expiring too soon

Deleting a PHP session

To destroy a session in PHP, use the session_destroy() function.

<?php
session_start();
session_destroy();
?>

Alternatively, you can delete a single session variable (if you don't want to destroy the whole session) using the unset() function.

Example:

<?php
session_start();
unset($_SESSION['name']);
?>

One disadvantage of using sessions is that they require server resources to store the session data. If a website has a large number of users, the server may become overloaded and slow down.

What are cookies?

Cookies are small text files that are stored on the user's computer (or mobile device) by the web browser.

When a user visits a website, the server can send a cookie to the user's browser. The browser stores the cookie and sends it back to the server with each subsequent request.

Similarly to sessions, cookies are commonly used to store information about the user, such as their login credentials or preferences.

Cookies are lightweight and require no server resources thus they do not affect the server's performance. However, cookies are less secure than sessions because they can be accessed and modified by the user.

Another disadvantage of using cookies is that they can be blocked or deleted by the user. This can lead to a poor user experience if the website relies heavily on cookies.

The total cookie size (across all cookies) should be less than or equal to 4093 bytes (approx 4Kbs).

Cookies are created using the setcookie() function in PHP.

Syntax

setcookie(name, value, expire, path, domain, secure, httponly);

Parameter Type Requirement Description
name String Required Specifies the name of the cookie.
value String Optional Specifies the value of the cookie.
expire Integer Optional This is a Unix timestamp specifying the time when the cookie should expire. Add the time in seconds that the cookie should take to expire to the result of calling time() function.
path String Optional Specifies the path on the server on which the cookie will be available. To access the cookie within the entire domain, set it to '/'. Else, set it to '/anything/' to be available only within the /anything/ directory and all sub-directories. The default value is the current directory that the cookie is being set in.
domain String Optional Specifies the domain or subdomain that the cookie will be available to. To make the cookie available to the whole domain (including all its subdomains), simply set the value to the domain name (eg. example.com).
secure Bool Optional Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. If set to true, the cookie will only be set if a secure connection exists.
httponly Bool Optional When true the cookie will be made accessible only through the HTTP protocol.

Creating a PHP Cookie

The following is an example of how to create a cookie in PHP:

<?php
setcookie("username", "John Doe", time() + (86400 * 30), "/");
?>

In this example, the cookie is named "username" and its value is "John Doe". The cookie will expire after 30 days (86400 seconds * 30), and it will be accessible to all pages on the website ("/" is the path for the cookie).

Retrieving Cookie Data

To retrieve/access the value of the cookie, we use the global variable $_COOKIE along with the name of the cookie as the array key.

Example

<?php
echo 'Hi '.$_COOKIE['username'].'! Great to see you again.';
?>

Output:
Hi John Doe! Great to see you again.

Updating Cookie Data

To update/modify the cookie, just use the setcookie() function again, now with a different value (and/or other parameters) for the same cookie name.

Example

<?php
setcookie("username", "James Bond", time() + (86400 * 50), "/");
?>

This code updates the cookie we had set above and changes its value from "John Doe" to "James Bond" and the expiration period from 30 to 50 days.

Deleting a Cookie

To delete a cookie in PHP, update it with an expiration date in the past.

Example

<?php
setcookie("username", "James Bond", time() - 3600);
?>

The above code deletes the cookie by setting its expiration date to one hour ago.

Note: The session_start() function (or setcookie() in case of a cookie) must be the very first thing in your document. Before any HTML tags.

Differences between PHP sessions and cookies

Below are the key differences between PHP sessions and cookies.

Sessions Cookies
Sessions store data on the server. Cookies store data on the user's device.
Sessions are generally more secure than cookies because the data is stored on the server-side, where it cannot be accessed or modified by the user. Cookies are stored on the client-side and can be accessed and modified by the user thus less secure.
Sessions can store larger amounts of data than cookies. Cookies have a size limit of 4KB, which means that they cannot store large amounts of data.

Conclusion

Sessions and cookies are powerful ways of maintaining user data across multiple pages in a web application. They can be used to remember user login credentials, store shopping cart content, store user preferences, track user behavior, and personalize content.

Although the two methods have similar applications in web development they differ significantly. In this article, you have learned each in detail and also their differences.