Authentication with Session in PHP

Authentication using sessions in PHP is a common way to manage user login and maintain a secure environment for web applications.

It involves storing user-specific information in server-side sessions to track and verify a user’s identity across multiple requests.

Key Concepts in Session-Based Authentication

Session:

  • A session is a way to store information (variables) for a specific user across multiple requests.
  • In PHP, sessions are implemented using $_SESSION, which stores data on the server and associates it with a unique session ID (usually saved as a cookie on the client side).

Authentication:

  • Authentication is the process of verifying the identity of a user. In session-based authentication:
    • The user submits their credentials (e.g., username and password) through a login form.
    • The server validates these credentials.
    • If valid, the server sets session variables to mark the user as authenticated.

Stateful Communication:

  • HTTP is a stateless protocol, meaning each request is independent. Sessions make it possible to maintain state by associating user data with a session ID across multiple requests.

Advantages of Session-Based Authentication

Secure Data Handling:

  • User data is stored on the server, not on the client, reducing the risk of tampering.

Persistence:

  • Sessions persist across multiple requests, allowing users to navigate an authenticated section of the site without re-logging in.

Ease of Implementation:

  • PHP provides built-in session handling, making it straightforward to implement.

Authentication script using sessions are here in login.php.

<?php
session_start();

// Define username and password in session

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

$_SESSION['password'] = '123456';

// Simple example of username/password validation directly in the script
if (isset($_POST['POST'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
        
    // Getting username and password from the session
    $sessionUsername = $_SESSION['username'];
    $sessionPassword = $_SESSION['username'];

    // Define your hardcoded credentials for comparison
    if ($username === $sessionUsername && $password === $sessionPassword) 		 	      {
        // Authentication successful
        $_SESSION['authenticated'] = true;
        $_SESSION['username'] = $username;
        header("Location: dashboard.php");
        exit;
    } else {
        // Authentication failed
        $error = "Invalid username or password.";
    }
}
?>

<form method="POST" action="#">
    <input type="text" name="username" placeholder="Username" required>
    <input type="password" name="password" placeholder="Password" required>
    <button type="submit">Login</button>
</form>

<?php if (isset($error)) echo "<p style='color:red;'>$error</p>"; ?>

Session Initialization

Starts a session or resumes an existing one. This is essential for using $_SESSION to store and retrieve session variables.

session_start();

Storing Username and Password in Session

These lines store a predefined username (algorithmroom) and password (123456) into the session variables.

This approach stores credentials in the session to act as a substitute for a database.

$_SESSION['username'] = 'algorithmroom';
$_SESSION['password'] = '123456';

Form Submission Handling

When the form is submitted, the POST method captures the input values:

  • $username: Contains the entered username.
  • $password: Contains the entered password.
if (isset($_POST['submit'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
  }

Retrieving Stored Credentials

These lines retrieve the hardcoded username and password from the session variables.

$sessionUsername = $_SESSION['username'];
$sessionPassword = $_SESSION['password'];

Validation Logic

The script compares the entered credentials ($username and $password) with the stored session values ($sessionUsername and $sessionPassword).

if ($username === $sessionUsername && $password === $sessionPassword) {
    // Authentication successful
    $_SESSION['authenticated'] = true;
    $_SESSION['username'] = $username;
    header("Location: dashboard.php");
    exit;
} else {
    // Authentication failed
    $error = "Invalid username or password.";
}

If they match, it sets $_SESSION['authenticated'] to true and redirects to dashboard.php.

Otherwise, it sets an error message: "Invalid username or password.".

HTML Form

A form collects the username and password input from the user. The POST method sends this data to the same script (action="#").

<form method="POST" action="#">
    <input type="text" name="username" placeholder="Username" required>
    <input type="password" name="password" placeholder="Password" required>
    <button type="submit" name="submit">Login</button>
</form>

Displaying Errors

If the $error variable is set due to failed validation, it displays the error message below the form.

<?php if (isset($error)) echo "<p style='color:red;'>$error</p>"; ?>

Redundant $_SESSION['username'] Assignment

This overwrites the session username with the user input unnecessarily.

$_SESSION['username'] = $username;

Dashboard Page (dashboard.php)

The dashboard is accessible only to authenticated users.

<?php

// start session
session_start();

if (!isset($_SESSION['authenticated'])) {
    header("Location: login.php");
    exit;
}

	echo "Welcome, " . htmlspecialchars($_SESSION['username']) . "!<br>";
?>

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

Start Session and Authentication Check

Without calling session_start(), you cannot access the $_SESSION superglobal to check session variables.

session_start();
if (!isset($_SESSION['authenticated'])) {
    header("Location: login.php");
    exit;
}

Checks if the $_SESSION['authenticated'] variable is not set or not. If the variable is not set, the user is redirected to the login.php page. And exit; ensures no further code is executed after the redirect.

Display Welcome Message

Retrieves the authenticated user's username stored in the session ($_SESSION['username']) and displays it.

echo "Welcome, " . htmlspecialchars($_SESSION['username']) . "!<br>";

htmlspecialchars():

  • Escapes special characters to prevent Cross-Site Scripting (XSS) attacks.
  • For example, if the username contains <script> tags, they will be displayed as plain text rather than being executed as a script.

Logout Link

Provides a hyperlink to the logout.php page.

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

Clicking this link will log the user out by destroying the session.


Logout Page (logout.php)

<?php
	session_start();
	session_unset();
	session_destroy();
	
	header("Location: login.php");
	exit;
?>

Start and unset all session Variables

It ensures access to the $_SESSION superglobal so the session variables can be manipulated or destroyed.

session_start();
session_unset();

For example, if $_SESSION['username'] and $_SESSION['authenticated'] were set during login, they are now cleared.

Destroy the Session

This completely destroys the session on the server.

session_destroy();

It invalidates the session ID, so the session cannot be resumed even if the user still has the session cookie.

This step ensures the user is fully logged out.

Redirect to Login Page

Redirects the user to the login.php page after logging out. Prevents the user from accessing the now invalid session.

header("Location: login.php");
exit;

exit;: Ensures no further code is executed after the redirect.