Ugacomp

How to work with Sessions and Cookies in PHP

Where necessary, you may need to have access to a VPS server so you can follow how to implement the steps in this article.  You can get a cheaper VPS Server from Contabo with 4vCPU cores, 8GM RAM, and 32TB Bandwidth for less than $5.50 per month. Get this deal here now

Table of Contents

Cloud VPS S

$5.50 Monthly
  • 4 vCPU Cores | 8GB RAM

CLOUD VPS M

$15.50 Monthly
  • 6 vCPU Cores | 16GB RAM

CLOUD VPS L

$17.50 Monthly
  • 8 vCPU Cores | 24GB RAM

When building dynamic and interactive web applications, it’s essential to maintain state across multiple requests. PHP offers powerful tools for achieving this through sessions and cookies. In this beginner’s guide, we will explore the basics of working with sessions and cookies in PHP, along with practical command examples.

What are Sessions in PHP?

When you interact with a website, it’s not just a single isolated request and response; there is often a need to remember things about you as you navigate through different pages. Imagine if every time you clicked a link or loaded a new page on a website, it didn’t recognize you anymore – you would have to log in repeatedly, and your shopping cart would empty every time you visited a new page. This is where sessions in PHP come into play.

A session, in the context of web development, is like a short-term memory for a website. It allows the server to remember information about you as you move from one page to another. This information can include your username, preferences, or anything else that needs to persist as you navigate the site.

Sessions provide a way to preserve data across subsequent HTTP requests. So, PHP sessions are server-side storage mechanisms that allow developers to store and retrieve user-specific information.

Start of a Session

When you visit a website, a session often starts. In PHP, you use the session_start() function to initiate a session. It’s like telling the server, “Hey, this person is here, and I want to remember some things about them.”

   <?php
   session_start();
   ?>

Starting a session is a fundamental step when working with sessions in PHP. Here are various scenarios with corresponding code examples:

Scenario 1: Starting a Simple Session

<?php
// Scenario 1: Starting a Simple Session

// Start a new session or resume the existing session
session_start();

// Now you can store and retrieve data in the session
?>

In this basic scenario, session_start() is called to initiate a new session or resume an existing one. Once the session has started, you can use $_SESSION to store and retrieve data.

Scenario 2: Starting a Session with Additional Configuration

<?php
// Scenario 2: Starting a Session with Additional Configuration

// Set session parameters before starting the session
session_name('MySession'); // Set a custom session name
session_set_cookie_params(3600, '/', '.example.com', true, true); // Set cookie parameters

// Start or resume the session
session_start();

// Now the session is started with custom configuration
?>

In this scenario, an additional session configuration is set before starting the session. The session_name() function is used to set a custom session name, and session_set_cookie_params() is used to customize cookie parameters.

  • Security Requirements: You might use this when security is a significant concern. Setting a custom session name, secure cookie, and HttpOnly flag helps protect against various types of attacks, such as session hijacking and cross-site scripting (XSS).
  • Cross-Domain or Subdomain Access: If your application spans multiple subdomains, setting the domain parameter allows the session to be shared across these subdomains.
  • Custom Session Management: When you need fine-grained control over session parameters, like expiration time or path, setting them explicitly ensures they meet your application’s requirements.

Scenario 3: Starting a Session Conditionally

<?php
// Scenario 3: Starting a Session Conditionally

// Check if a session is already active
if (session_status() == PHP_SESSION_NONE) {
    // Start the session if not already started
    session_start();
}

// Now the session is either started or resumed
?>

Here, session_status() is used to check if a session is already active. If the session is not active (PHP_SESSION_NONE), session_start() is called to start or resume the session.

Scenario 4: Regenerating the Session ID

<?php
// Scenario 4: Regenerating the Session ID

// Start or resume the session
session_start();

// Regenerate the session ID for security purposes
session_regenerate_id(true);

// Now the session has a new ID
?>

In this scenario, after starting or resuming the session, session_regenerate_id(true) is called to regenerate the session ID. This is often done for security reasons to prevent session fixation attacks.

Storing Information

Once a session has started, you can store information about the user in a special variable called $_SESSION. This variable persists across different pages as long as the session is active.

   <?php
   // Storing a username in the session
   $_SESSION['username'] = 'JohnDoe';
   ?>

Sessions in PHP are commonly used to store and retrieve various types of information about a user as they navigate through a website. Below are code examples demonstrating different types of information that can be stored in sessions.

Storing User Information

<?php
// Start or resume the session
session_start();

// Storing user information in the session
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'JohnDoe';
$_SESSION['email'] = '[email protected]';
?>

In this example, user-related information such as user ID, username, and email address is stored in the session. This data can be used to personalize the user’s experience across different pages.

Storing Preferences

<?php
// Start or resume the session
session_start();

// Storing user preferences in the session
$_SESSION['theme'] = 'dark';
$_SESSION['language'] = 'en';
?>

Here, user preferences like the selected theme and language are stored in the session. This information allows the application to maintain a consistent look and feel based on the user’s preferences.y

Storing Shopping Cart Items

<?php
// Start or resume the session
session_start();

// Storing shopping cart items in the session
$_SESSION['cart'] = [
    ['product_id' => 1, 'quantity' => 2],
    ['product_id' => 3, 'quantity' => 1],
];
?>

For e-commerce websites, the shopping cart contents can be stored in the session. This enables users to add items to their cart and maintain the cart state across different pages.

Storing Authentication Status

<?php
// Start or resume the session
session_start();

// Storing authentication status in the session
$_SESSION['is_authenticated'] = true;
?>

To keep track of whether a user is authenticated or not, a simple boolean flag can be stored in the session. This helps in controlling access to certain parts of the website that require authentication.

Storing Last Activity Time

<?php
// Start or resume the session
session_start();

// Storing last activity time in the session
$_SESSION['last_activity'] = time();
?>

For session management and user activity tracking, the last activity time can be stored in the session. This information is useful for implementing session timeout functionality.

Where are sessions stored?

PHP sessions, by default, are not stored directly in databases. Instead, they are stored on the server’s file system. When a session is started using session_start(), PHP creates a unique session file on the server for each user. The session data, which includes variables stored in $_SESSION, is serialized and stored in this file.

The session files are typically stored in a designated directory on the server. The file name is often generated based on the session ID, which is sent to the client as a cookie (usually named “PHPSESSID”) or as part of the URL.

However, PHP provides options to customize how sessions are handled, and one such option is to use a database to store session data. This is known as “custom session handling.”

Custom Session Handling with Database Storage

To store sessions in a database, you need to implement custom session handling using the session_set_save_handler() function. This involves creating functions to manage session data operations, such as opening, closing, reading, writing, and destroying sessions.

Here is a simplified example of using a MySQL database to store session data:

<?php
// Custom session handling functions
function custom_session_open($savePath, $sessionName) {
    // Connect to your database
    // Create a table to store session data if not already exists
    return true;
}

function custom_session_close() {
    // Close the database connection
    return true;
}

function custom_session_read($sessionId) {
    // Read session data from the database
    // Return the session data or an empty string if the session does not exist
}

function custom_session_write($sessionId, $data) {
    // Write session data to the database
    // Update if the session already exists, or insert if it's a new session
}

function custom_session_destroy($sessionId) {
    // Delete session data from the database when a user logs out or the session expires
}

function custom_session_gc($maxLifetime) {
    // Delete old session data from the database to perform garbage collection
}

// Set custom session handling functions
session_set_save_handler(
    'custom_session_open',
    'custom_session_close',
    'custom_session_read',
    'custom_session_write',
    'custom_session_destroy',
    'custom_session_gc'
);

// Start the session
session_start();
?>

In this example, you would need to replace the placeholder functions with actual database interactions. Keep in mind that implementing custom session handling with a database introduces additional complexity and requires careful consideration of security and performance implications. It’s often recommended to use built-in session handling unless specific requirements dictate otherwise.

Storing sessions in databases becomes relevant in scenarios where the default file-based session storage might be insufficient or impractical. Here are situations where storing sessions in databases is advantageous:

Load Balancing and Server Clustering

When a web application is distributed across multiple servers for load balancing or clustering. This is because file-based session storage can lead to synchronization issues and inconsistency between servers. Storing sessions in a centralized database ensures that session data is accessible and consistent across all servers.

Shared Hosting Environments

In shared hosting environments where file-based storage might expose session data to other users on the same server. Storing sessions in a database provides a more secure option, as it ensures the isolation of session data between different users on shared hosting.

Improved Scalability

When the application expects a large number of concurrent users, and optimizing for scalability is a priority. Database systems are designed to handle large volumes of data and offer better scalability options compared to file systems. Storing sessions in a database can enhance performance and scalability.

Advanced Caching and Query Capabilities

When you need advanced caching mechanisms or query capabilities for session data. Database systems often provide features like caching and powerful querying, which can be beneficial for managing and analyzing session data in more sophisticated ways.

Session Data Security

When heightened security requirements demand more control over session data and access. Storing sessions in a database allows for stronger access controls, encryption, and auditing mechanisms, enhancing overall session data security.

Compliance with Regulations

When dealing with compliance requirements, such as GDPR, HIPAA, or other data protection regulations. Storing sessions in a database allows for easier management of user consent, data retention policies, and compliance with regulations that govern the storage and handling of personal information.

Longer Session Lifetimes

When sessions need to persist for an extended period or when implementing features like “remember me” functionality. Database-backed sessions can be more suitable for longer session lifetimes, as they can be managed more efficiently and securely compared to file-based storage.

It’s important to note that while storing sessions in databases offers advantages in specific scenarios, it also introduces complexities such as potential performance overhead, increased latency, and additional configuration requirements. The decision to use database-backed sessions should be based on a careful assessment of the application’s specific needs and infrastructure considerations.

Retrieving Session Information

Retrieving information from PHP sessions is a crucial part of using sessions effectively. Below are code examples demonstrating how to retrieve various types of information stored in sessions.

Retrieving User Information

<?php
// Start or resume the session
session_start();

// Retrieving user information from the session
$userID = $_SESSION['user_id'];
$username = $_SESSION['username'];
$email = $_SESSION['email'];

// Using the retrieved information
echo "Welcome, $username! Your email is $email, and your user ID is $userID.";
?>

In this example, user-related information previously stored in the session (such as user ID, username, and email) is retrieved and used to personalize a welcome message.

Retrieving Preferences

<?php
// Start or resume the session
session_start();

// Retrieving user preferences from the session
$theme = $_SESSION['theme'];
$language = $_SESSION['language'];

// Using the retrieved preferences
echo "Your selected theme is $theme, and your preferred language is $language.";
?>

Here, user preferences stored in the session (like theme and language) are retrieved and used to customize the user experience.

Retrieving Shopping Cart Items

<?php
// Start or resume the session
session_start();

// Retrieving shopping cart items from the session
$cartItems = $_SESSION['cart'];

// Displaying the retrieved shopping cart items
echo "Your shopping cart contains:";
foreach ($cartItems as $item) {
    echo "Product ID: {$item['product_id']}, Quantity: {$item['quantity']}";
}
?>

For e-commerce scenarios, the shopping cart contents stored in the session are retrieved and displayed to the user.

Retrieving Authentication Status

<?php
// Start or resume the session
session_start();

// Retrieving authentication status from the session
$isAuthenticated = $_SESSION['is_authenticated'];

// Checking authentication status
if ($isAuthenticated) {
    echo "You are authenticated. Welcome!";
} else {
    echo "You need to log in to access this content.";
}
?>

In this example, the authentication status stored in the session is retrieved to determine whether the user is authenticated or not.

Retrieving Last Activity Time

<?php
// Start or resume the session
session_start();

// Retrieving last activity time from the session
$lastActivityTime = $_SESSION['last_activity'];

// Checking for session timeout
$timeoutSeconds = 1800; // 30 minutes
if (time() - $lastActivityTime > $timeoutSeconds) {
    echo "Your session has timed out. Please log in again.";
    // Optionally, you may destroy the session or take other actions here
} else {
    echo "You are still active. Carry on!";
}
?>

In this example, the last activity time stored in the session is retrieved and used to check for session timeout.

These examples showcase how information stored in PHP sessions can be easily retrieved and utilized within your web application.

End of a Session

Sessions typically end when you close your browser or after a period of inactivity. You don’t have to explicitly “log out” of a session; it happens automatically.

Working with Cookies

Cookies are small pieces of data stored on a user’s device by the web browser. They are used to remember information about the user, such as preferences or login status, between different visits to a website.

Setting Cookies in PHP:

You can set cookies in PHP using the setcookie() function. Here’s a simple example:

<?php
// Set a cookie with a name, value, and expiration time
setcookie('user', 'JohnDoe', time() + 3600, '/');
?>

In this example:

  • 'user' is the name of the cookie.
  • 'JohnDoe' is the value associated with the cookie.
  • time() + 3600 sets the expiration time of the cookie. In this case, it’s set to expire in one hour.
  • '/' specifies the path on the domain where the cookie is available.

Retrieving Cookies in PHP

Once a cookie is set, you can retrieve its value using the $_COOKIE superglobal. Here’s an example:

<?php
// Retrieve the value of the 'user' cookie
$user = $_COOKIE['user'];

// Output the retrieved value
echo "Welcome back, $user!";
?>

In this example, $_COOKIE['user'] retrieves the value of the ‘user’ cookie, and it’s then used in the output.

Updating Cookies

You can update a cookie by setting a new value or expiration time using setcookie(). For example:

<?php
// Update the value of the 'user' cookie
setcookie('user', 'JaneDoe', time() + 3600, '/');

// Retrieve the updated value
$user = $_COOKIE['user'];

// Output the updated value
echo "Welcome back, $user!";
?>

In this case, the value of the ‘user’ cookie is updated to ‘JaneDoe’.

Deleting Cookies

To delete a cookie, you can set its expiration time to a time in the past:

<?php
// Delete the 'user' cookie by setting its expiration time to the past
setcookie('user', '', time() - 3600, '/');

// Check if the cookie is now empty
if (empty($_COOKIE['user'])) {
    echo "Cookie 'user' has been deleted.";
} else {
    echo "Cookie 'user' still exists.";
}
?>

Setting the expiration time to a past value effectively deletes the cookie. The example checks if the cookie is empty to confirm its deletion.

What is the difference between cookies and Sessions?

Sessions are a server-side mechanism for maintaining stateful information about a user’s interactions with a website. When a session is initiated, a unique identifier (usually a session ID) is assigned to the user. This identifier is often stored in a cookie on the client side, but the actual data associated with the session is stored on the server. Sessions allow for the persistence of user-specific information across multiple requests and pages.

Sessions are more secure than cookies because the session data is stored on the server. Additionally, sessions are not limited by the size constraints of cookies, making them suitable for storing larger amounts of data. They are commonly used for tasks such as user authentication, storing shopping cart contents, and maintaining user preferences.

Cookies, on the other hand, are small pieces of data stored on the client’s browser. They are sent back and forth between the client and server with each HTTP request. Cookies are often used to store user-specific information locally, such as user preferences, tracking data, or authentication tokens. Unlike sessions, cookies can persist beyond a single session and can have expiration times set.

While cookies are convenient for storing small amounts of data on the client side, they pose security concerns. Information stored in cookies is visible and modifiable by the client, making them susceptible to attacks like cross-site scripting (XSS) or data tampering. To enhance security, certain flags, such as HttpOnly and Secure, can be set when creating cookies.

Session and Cookie Security

When working with sessions and cookies, it’s crucial to consider security. Always validate and sanitize user input to prevent attacks like session hijacking or cookie tampering.

Session Security

To enhance session security, regenerate the session ID after a user logs in:

<?php
// Start or resume the session
session_start();

// Regenerate the session ID
session_regenerate_id(true);
?>

Cookie Security

When setting cookies, use the Secure and HttpOnly flags to enhance security:

<?php
// Set a secure and HTTP-only cookie
setcookie('user', 'Bob', time() + 3600, '/', '', true, true);
?>

The Secure flag ensures that the cookie is only sent over HTTPS, while the HttpOnly flag prevents JavaScript access to the cookie.

Hire us to handle what you want

Hire us through our Fiverr Profile and leave all the complicated & technical stuff to us. Here are some of the things we can do for you:

  • Website migration, troubleshooting, and maintenance.
  • Server & application deployment, scaling, troubleshooting, and maintenance
  • Deployment of Kubernetes, Docker, Cloudron, Ant Media, Apache, Nginx,  OpenVPN, cPanel, WHMCS, WordPress, and more
  • Everything you need on AWS, IBM Cloud, GCP, Azure, Oracle Cloud, Alibaba Cloud, Linode, Contabo, DigitalOcean, Ionos, Vultr, GoDaddy, HostGator, Namecheap, DreamHost, and more.
 

We will design, configure, deploy, or troubleshoot anything you want. Starting from $10, we will get your job done in the shortest time possible. Your payment is safe with Fiverr as we will only be paid once your project is completed.