1. Home
PHP

PHP Tutorials : A Comprehensive Guide

Master PHP with our in-depth tutorials. From beginner to advanced topics, explore essential concepts and upskill yourself.

  • 7
  • 1
right-top-arrow
6

Session in PHP

Updated on 04/10/2024434 Views

Sessions play a crucial role in web development, enabling websites to maintain user-specific data across multiple pages or visits. In PHP, sessions are integral for building interactive and personalized web applications. Understanding how sessions work and how to implement them effectively is essential for any PHP developer. In this tutorial, we will talk about sessions in PHP, covering their concept and examples in detail.

Overview

Let us now define the session in PHP. A session in PHP is a way to preserve data across subsequent HTTP requests. It allows the server to store user-specific information, such as login credentials, preferences, or shopping cart items, throughout the user's interaction with the website. Unlike cookies, which are stored on the client side, sessions are managed on the server side, making them more secure.

How Sessions Work

When a user first accesses a PHP page, the system generates a unique session identifier (SID) for that user. Typically, a cookie named PHPSESSID stores this identifier, but users can also pass it through URL parameters. The server uses this session ID to associate subsequent requests from the same user with their session data.

Sessions Typically Involve the Following Steps

Session Initialization: When a session starts, PHP generates a unique session ID for the user. If the user already has a session ID (e.g., from a previous visit), PHP retrieves the existing session data associated with that ID.

Data Storage: During the session, PHP allows developers to store and retrieve data in the $_SESSION superglobal array. This array persists across multiple page loads within the same session.

Session Termination: Sessions can be terminated explicitly by calling session_destroy() or implicitly after a specified period of inactivity (session timeout).

Now let us explore the PHP session examples.

Example 1: Basic Session Usage

<?php

// phpsession_start session

session_start();

// Set session variables

$_SESSION['username'] = 'john_doe';

$_SESSION['email'] = 'john@example.com';

// Access session variables

echo 'Username: ' . $_SESSION['username'] . '<br>';

echo 'Email: ' . $_SESSION['email'] . '<br>';

// Unset session variables

unset($_SESSION['email']);

// Destroy the session

session_destroy();

?>

In this example:

  • We start a session using session_start().
  • We set session variables using the $_SESSION superglobal array.
  • We access and display session variables.
  • We unset one of the session variables using unset().
  • Finally, we destroy the session using session_destroy().

Example 2: Using Sessions for User Authentication

<?php

session_start();

// Simulating user authentication

$username = 'admin';

$password = 'password';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

if ($_POST['username'] === $username && $_POST['password'] === $password) {

$_SESSION['authenticated'] = true;

header('Location: dashboard.php');

exit;

} else {

$error = 'Invalid username or password';

}

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Login</title>

</head>

<body>

<h2>Login</h2>

<?php if (isset($error)) echo '<p>' . $error . '</p>'; ?>

<form method="post">

<label for="username">Username:</label>

<input type="text" id="username" name="username" required><br>

<label for="password">Password:</label>

<input type="password" id="password" name="password" required><br>

<button type="submit">Login</button>

</form>

</body>

</html>

In this example:

  • We simulate user authentication with a hardcoded username and password.
  • If the user submits the correct credentials, we set a session variable 'authenticated' to true and redirect them to a dashboard page.
  • If the authentication fails, we display an error message.

Example 3: Session Timeout Configuration

<?php

// Set session timeout to 30 minutes

ini_set('session.gc_maxlifetime', 1800);

session_start();

?>

In this example:

  • We use the ini_set() function to configure the session timeout to 30 minutes (1800 seconds).
  • We then start the session as usual.

How to Destroy a Session in PHP?

In PHP, destroying a session involves clearing all session data associated with the current session and removing the session cookie from the client's browser. This ensures that the user's session is terminated, and they are effectively logged out. Let's explore how to destroy a PHP session program with an example:

<?php

// Start the session

session_start();

// Check if the user is logged in

if(isset($_SESSION['user_id'])) {

// Unset all session variables

$_SESSION = array();

// Destroy the session cookie

if (ini_get("session.use_cookies")) {

$params = session_get_cookie_params();

setcookie(session_name(), '', time() - 42000,

$params["path"], $params["domain"],

$params["secure"], $params["httponly"]

);

}

// Destroy the session

session_destroy();

// Redirect the user to the login page or any other desired page

header("Location: login.php");

exit();

} else {

// If the user is not logged in, redirect them to the login page

header("Location: login.php");

exit();

}

?>

In this example:

  • We start the session using session_start() to ensure we have access to session variables.
  • We check if the user is logged in by verifying the presence of a specific session variable (e.g., 'user_id'). This check could be based on any criteria specific to your application.
  • If the user is logged in, we proceed to destroy the session:
  • We unset all session variables by setting $_SESSION to an empty array.
  • We destroy the session cookie by setting an expired cookie with a past expiration time. This ensures that the session cookie is removed from the client's browser.
  • We destroy the session itself using session_destroy().

After destroying the session, we can redirect the user to a login page or any other desired page. This step is essential to guide the user to the appropriate action after the PHP session login and logout.

If the user is not logged in, we also redirect them to the login page to maintain the expected behavior of the application.

How to Send Session Without Cookies in PHP

Here we discuss the steps involved in sending sessions without cookies in PHP.

Step 1: Configure PHP Settings

Ensure that URL rewriting for sessions is enabled in your PHP configuration. You can do this by setting session.use_trans_sid to 1. You can do this either in your php.ini file or using the ini_set() function.

// Enable URL rewriting for sessions

ini_set('session.use_trans_sid', 1);

Step 2: Start the Session

Before you can create a session in PHP, you need to start the session using session_start().

// Start the session

session_start();

Step 3: Append Session ID to URLs

For each URL in your application, append the session ID as a query parameter.

<a href="page.php?PHPSESSID=<?php echo session_id(); ?>">Link</a>

Step 4: Retrieve Session ID from URLs

In the pages that receive requests, retrieve the session ID from the query parameters and set it using session_id() before starting the session.

// Set the session ID from the URL parameter

if(isset($_GET['PHPSESSID'])) {

session_id($_GET['PHPSESSID']);

}

// Start the session

session_start();

Step 5: Use Hidden Form Fields to Transmit Session ID

When submitting forms, include a hidden field to transmit the session ID.

<form action="process.php" method="post">

<input type="hidden" name="PHPSESSID" value="<?php echo session_id(); ?>">

<!-- Other form fields -->

<button type="submit">Submit</button>

</form>

In the processing script (process.php), retrieve the session ID from the hidden field and set it before starting the session.

// Set the session ID from the hidden form field

if(isset($_POST['PHPSESSID'])) {

session_id($_POST['PHPSESSID']);

}

// Start the session

session_start();

Step 6: PHP Session Handling

Ensure the security of transmitted session IDs by treating them as sensitive data. Always transmit session IDs over HTTPS to prevent interception. Implement measures to prevent session fixation and session hijacking attacks.

PHP Login Session with Database

Implementing a PHP login session with a database involves several steps, including establishing a connection to the database, validating user credentials, setting up session variables upon successful login, and protecting restricted pages from unauthorized access. Below is an example of how you can achieve this:

Database Setup

Assuming you have a MySQL database with a table named users containing fields ID, username, and password. Ensure that passwords are hashed for security.

<?php

session_start();

// Database connection

$servername = "localhost";

$username = "username";

$password = "password";

$database = "database";

$conn = new mysqli($servername, $username, $password, $database);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

}

// Check if the form is submitted

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$username = $_POST['username'];

$password = $_POST['password'];

// Retrieve user data from database

$sql = "SELECT * FROM users WHERE username='$username'";

$result = $conn->query($sql);

if ($result->num_rows == 1) {

$row = $result->fetch_assoc();

// Verify password

if (password_verify($password, $row['password'])) {

// Password is correct, start session and set session variables

$_SESSION['loggedin'] = true;

$_SESSION['username'] = $username;

$_SESSION['user_id'] = $row['id'];

// Redirect to dashboard or any authenticated page

header("Location: dashboard.php");

exit();

} else {

// Password is incorrect

$error = "Incorrect username or password.";

}

} else {

// User not found

$error = "User not found.";

}

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Login</title>

</head>

<body>

<h2>Login</h2>

<?php if (isset($error)) echo '<p>' . $error . '</p>'; ?>

<form method="post">

<label for="username">Username:</label>

<input type="text" id="username" name="username" required><br>

<label for="password">Password:</label>

<input type="password" id="password" name="password" required><br>

<button type="submit">Login</button>

</form>

</body>

</html>

Dashboard Page (dashboard.php)

<?php

session_start();

// Check if user is logged in

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {

header("Location: login.php");

exit();

}

// Display welcome message

$username = $_SESSION['username'];

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Dashboard</title>

</head>

<body>

<h2>Welcome, <?php echo $username; ?>!</h2>

<p>This is your dashboard.</p>

<a href="logout.php">Logout</a>

</body>

</html>

Logout Script (logout.php)

<?php

session_start();

// Unset all session variables

$_SESSION = array();

// Destroy the session

session_destroy();

// Redirect to login page

header("Location: login.php");

exit();

?>

<?php

session_start();

// Unset all session variables

$_SESSION = array();

// Destroy the session

session_destroy();

// Redirect to login page

header("Location: login.php");

exit();

?>

This example demonstrates a basic login in PHP with session land in a MySQL database. It validates user credentials against the database, sets session variables upon successful login, and restricts access to authenticated users. Additionally, it includes a logout functionality to destroy the session and redirect the user to the login page.

Wrapping Up

Developers use sessions in PHP to build dynamic and interactive web applications. By understanding how sessions work, you can create personalized user experiences and maintain user-specific data securely.

FAQ

Q: What is a session in PHP?

A: A session in PHP is a way to preserve data across multiple HTTP requests for a single user.

Q: How to get session data in PHP?

A: Session data in PHP can be retrieved using the $_SESSION superglobal array.

Q: Where is the session stored in PHP?

A: In PHP, session data is typically stored on the server side in files or in a database, depending on the configuration.

Q: What is a session with an example?

A: A session in PHP allows storing user-specific data throughout their interaction with a website, such as login credentials or shopping cart items.

Q: How to pause a session in PHP?

A: Sessions can be paused in PHP using session_write_close() to temporarily stop writing session data.

Q: What are the advantages of sessions in PHP?

A: Advantages of sessions in PHP include maintaining user-specific data, facilitating user authentication, and enabling personalized experiences.

Q: How to clear a session in PHP?

A: To clear session data in PHP, you can use session_unset() to unset all session variables.

Q: How to destroy a session in PHP?

A: A session in PHP can be destroyed using session_destroy(), which removes all session data and destroys the session cookie.

Q: How to restart a session in PHP?

A: To restart a session in PHP, you can call session_start() again after destroying the session.

Q: How to avoid multiple sessions in PHP?

A: To avoid multiple sessions in PHP, ensure that session_start() is called only once per session and prevent session fixation attacks by regenerating session IDs when necessary.

Talk to Career Expert
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .