Page Content

Tutorials

PHP Session Based Authentication For Secure Login

Using PHP to access a database from a web application frequently entails handling user identity and data over several pages, necessitating knowledge of state maintenance and session based authentication.

What’s Session Based Authentication?

Session authentication identifies users in subsequent requests after login. These steps are typical for session authentication:

  • Browser-based login requests with ID and password are sent to the server.
  • If the authentication is correct, the server starts a session. Servers and Cookies store session data. This sample stores it in RAM, but apps usually use databases or other storage.
  • The server tells the browser the session is established.
  • The browser makes server queries with session information to authenticate the user.
  • Users are authorised once the server confirms session information in the request.
  • The server informs the browser that the user is authorised to access certain actions or resources.
  • User logout requests are sent to the server by the browser.
  • The server deletes the session and Cookie, invalidating session data.
  • The server informs the browser that the session has ended.

Maintaining State

HTTP is stateless and underpins web communication. After serving a page, a web server does not immediately remember that the same client is making subsequent requests.

However, online applications that require user logins, shopping carts, or customised content must preserve “state” that is, remembering user details across requests. If you don’t save state, you can’t remember user preferences or shopping cart items.

With PHP cookies, which are sent by PHP via the setcookie() method and saved in the browser, data may be easily maintained between pages in a web application. The cookie is returned to the server when the browser requests the same domain again. Cookies can retain information for a long period, but they can be fabricated, therefore don’t store authentication information in them.

PHP manages state better, especially user sessions and authentication.

Using Sessions to preserve data across pages

An application can save data for the current “session,” which is usually defined as one user signed into the program, using a PHP session. Sessions offer persistent variables that can be accessed from many application pages and even throughout a user’s repeated visits to the website. This facilitates the creation of multi-page forms, the storing of permanent user preferences, and the saving of user authentication data.

Each user is given a unique session ID, which is how sessions operate. By default, PHP generates this session ID as a hexadecimal string that is an MD5 hash of the remote IP address, the current time, plus a little bit of randomness. Usually, this session ID is saved in a cookie with the default name PHPSESSID. Although utilising cookies is normally preferred for security reasons, the session ID might occasionally be propagated in URLs if cookies are not supported or are disabled.

In contrast to cookies, the session data itself is kept on the server. This data can be retrieved using the session ID as a key. You can set PHP to store session data in a database by writing custom methods, but by default, session variables are kept in flat files on the server.

The session_start() method must be used to launch the session before you may use sessions in PHP. Before any output is transmitted to the browser, this function needs to be called at the very start of your script. Using session_start() imports an existing session or launches a new one. After the session starts, the associative array $_SESSION can set and access session variables.

Example of setting a variable and starting a session:

<?php
session_start(); // Start or resume the session 
// Set a session variable 
$_SESSION["username"] = "John Doe";
$_SESSION["user_token"] = "d5f1df5b4dfb8b8d5f";
echo "Session variables saved successfully!"; //
?>

Starting a session, registering variables (by adding them to $_SESSION), utilising those variables, and finally deregistering them or killing the session are the standard processes for using sessions.

<?php
session_start(); // Start or resume the session 
// Access the session variable 
if (isset($_SESSION["username"])) {
    echo "Welcome back, " . $_SESSION["username"] . "!";
} else {
    echo "Welcome, guest.";
}
?>

Implementing user login and logout

One of the most common uses of session control is tracking users after login. Authentication involves comparing a user’s login and password to a database of known users.

A standard session-based login procedure entails:

  1. Giving the user a login form.
  2. Verifying the entered login and password against database credentials after the form is submitted.
  3. Starting a session and creating a session variable (or variables) to show that the user is logged in and maybe save user-specific data, such as their username or user level, if the credentials are legitimate.

Assuming a database connection $db_conn and successful credential validation, the following is a condensed illustration of the login processing logic:

<?php
session_start(); // Start or resume the session 
if (isset($_POST['userid']) && isset($_POST['password'])) { // Check if login form was submitted 
    $userid = $_POST['userid'];
    $password = $_POST['password'];
    // Assume $db_conn is a valid database connection
    // Assume credential checking logic here (e.g., querying 'authorized_users' table) 
    // using prepared statements is recommended for security
    // Simplified check:
    // $query = "select * from authorized_users where name=? and password=sha1(?)";
    // $stmt = $db_conn->prepare($query);
    // $stmt->bind_param('ss', $userid, $password);
    // $stmt->execute();
    // $result = $stmt->get_result();
    $query = "select * from authorized_users where name='$userid' and password=sha1('$password')"; // 
    $result = $db_conn->query($query); // 
    if ($result->num_rows > 0) { // If user found in database 
        // Register the user id in the session 
        $_SESSION['valid_user'] = $userid; // 
        // Optionally set other session variables like user level 
        // $_SESSION['user_level'] = ;
        // Regenerate session ID after successful login for security 
        session_regenerate_id(true); // `true` deletes the old session file
        // Redirect to a members-only page - Note: header() must be called before any output
        // header("Location: members_only.php");
        // exit();
    } else {
        // User/password combination is wrong 
        // Redirect to an error page or show error message 
        // header("Location: fail.php");
        // exit();
    }
    $db_conn->close(); // Close database connection 
}
// Rest of the page content (e.g., display login form if not logged in) 
?>

Usually, a script that deletes the user’s session state is used to log out. This typically entails erasing the session itself and eliminating the session variables that show the user is logged in.

You can use the unset() function to eliminate particular session variables:

<?php
session_start(); // Access the current session 
// Unset a specific session variable 
unset($_SESSION['valid_user']);
?>

Use session_destroy() to end the session as a whole. Although session_destroy() normally deletes the session data store, it is common practice to set the $_SESSION array to an empty array ($_SESSION = array()); before session_destroy() to clear all session variables. The session cookie may also expire.

This is an illustration of a logout script:

<?php
session_start(); // Access the current session 
// Store the user's old username before destroying the session (optional) 
$old_user = $_SESSION['valid_user'] ?? '';
// Unset all session variables
$_SESSION = array(); // Also helps ensure variables are cleared 
// Get session cookie parameters 
$params = session_get_cookie_params();
// Destroy the session cookie by setting its expiration time to the past 
setcookie(session_name(), '', time() - 42000,
    $params["path"], $params["domain"],
    $params["secure"], $params["httponly"]
);
// Destroy the session data on the server
if (session_status() == PHP_SESSION_ACTIVE) { // Optional check for PHP 7.1+ 
    session_destroy(); // 
}
// Redirect the user after logging out - Header must be sent before output
header("Location: index.php"); // Redirect to home page 
exit(); // Stop script execution
?>

Creating members-only pages based on session state

You verify the session state at the start of each protected page to limit access to certain pages so that only members who are logged in can view them. The session variable that is established after a successful login serves as a “security pass” or flag.

The fundamental reasoning is:

  1. Open the protected page to begin the session.
  2. Verify a user_level or check isset($_SESSION[‘valid_user’]) to see if the session variable identifying a logged-in user exists and has the expected value.
  3. Return the user to the login page or show an error notice if the session variable is not set or if the value is not appropriate for the needed access level.
  4. Permit the script to proceed and show the members-only material if the session variable shows that the user is authorised.

This is an illustration of how to secure a page:

<?php
session_start(); // Access the current session 
// Check if the user is logged in (e.g., by checking the 'valid_user' session variable) 
// Or check for a specific user level for administration pages
if (!isset($_SESSION['valid_user'])) { // Check if the flag is absent 
    // If not logged in, display an error message or redirect 
    echo "You are not authorized to view this page."; // 
    // Alternatively, redirect:
    // header("Location: login.php"); // Redirect to the login page 
    exit(); // Terminate processing 
}
// If the session variable is set, the user is authorized 
echo "Welcome to the members-only area, " . $_SESSION['valid_user']. "!"; //
// Members-only content goes here.
?>

You can regulate access to various areas of your web application by utilising sessions to maintain authentication status and verify this state on protected pages. To offer different access privileges (e.g., for regular members versus administrators), the session variable can store distinct values (e.g., user_level).

Security Considerations

It’s crucial to protect sessions even though they’re more secure than explicitly storing authentication information in cookies. Using session_regenerate_id() is a crucial procedure. By reducing the amount of time a stolen ID is valid, this function helps prevent session fixation and hijacking assaults by invalidating the current session ID and creating a new one. Whenever a user’s privilege level changes for example, following a successful login this function should be called.

Additional security methods discussed include using session timeouts to immediately log out inactive users and verifying the browser fingerprint (such as the user agent or IP address, albeit IP can change) on every request. For further security, it is also advised to use a server that has SSL enabled.

Index