Skip to main content
March 23, 2026Noble Desktop Publishing Team/11 min read

Sessions: Free PHP & MySQL Tutorial

Master PHP Sessions for Dynamic Web Applications

Core PHP Session Concepts

Session Variables

Store user data across multiple pages within a single browser session. Essential for maintaining state in stateless HTTP.

Password Protection

Secure pages by checking session status before allowing access. Redirect unauthorized users to login forms automatically.

User Authentication

Implement login and logout functionality using session management. Control user access throughout your application.

Topics Covered in This PHP & MySQL Tutorial:

Starting a Session, Using Session Variables, Log In/log Out, Destroying Session Variables

Exercise Overview

The World Wide Web operates as a stateless medium, meaning that each HTTP request exists in isolation—one page has no inherent knowledge of another page's data or state. Variables created on one page vanish when users navigate elsewhere, creating a fundamental challenge for web applications that need to maintain user context across multiple pages.

Session variables provide the elegant solution to this stateless problem. When you establish a session variable, it persists across your entire application for an individual user's browsing session—typically until they log out, close their browser, or the session expires. This capability proves invaluable for numerous scenarios: maintaining user authentication states, preserving shopping cart contents, storing user preferences, and tracking workflow progress through multi-step processes.

In this comprehensive exercise, we'll build a practical login/logout system with password-protected pages, demonstrating how sessions form the backbone of modern web application security and user experience.

Understanding Stateless Web

The WWW is stateless, meaning pages don't remember each other. Session variables solve this by maintaining user data across your application for individual users until they log out or close their browser.

Getting Started

  1. Open index.php from the session-start folder in the phpclass folder.

  2. In a browser go to:

    • Mac: localhost:8888/phpclass/session-start/index.php
    • Windows: localhost/phpclass/session-start/index.php
  3. Click around and explore the site. We have a mock news portal with a non-functional login form. Our goal is to implement session-based authentication that password-protects all pages except the index page, while providing seamless login and logout functionality.

Initial Setup Requirements

0/4

Password-Protecting Some Pages

We'll start by creating a reusable authentication module that checks session status and user login state. This centralized approach ensures consistent security across your application and makes maintenance straightforward.

  1. Create a new page called passwordProtection.php and save it into the session-start folder in the phpclass folder.

  2. To access session variables, you must invoke the session_start() function. This critical function has strict requirements that, if violated, will break your application:

    • It must be the very first thing at the top of the page before any other output has been sent to the browser. Otherwise you will get an error that headers have already been sent.
    • You can only run the function once per page—multiple calls will generate errors.
  3. In passwordProtection.php add the following code:

    <?php 
    
       session_start(); 
    
    ?>

    This initializes the session management system for the current page.

  4. Next, we'll implement the authentication logic. Our application uses a session variable called loggedIN as the authentication flag. When loggedIN equals true, the user has valid access. If it's false or undefined, they lack authorization. Add the following code:

    <?php
    
       session_start(); 
    
       if (! isset($_SESSION['loggedIN']) ) {
    
         header('Location: login.php');
         exit();
    
      }
    
    ?>

    This security check redirects unauthorized users to the login page and immediately halts script execution to prevent any protected content from loading.

    The header() function sends raw HTTP header information to the browser. The "Location:" header triggers an automatic redirect to the specified page.

  5. Save the page.

  6. Now let's test our protection system. Open entertainment.php from the session-start folder.

  7. At the very top of the page, before any existing content, add this include statement:

    <?php require_once('passwordProtection.php'); ?>

    The require_once function includes our authentication module while preventing duplicate inclusions.

  8. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/session-start/entertainment.php
    • Windows: localhost/phpclass/session-start/entertainment.php

    Instead of seeing the content, you'll be automatically redirected to the login page, confirming our protection works.

  9. Let's secure all remaining content pages. Switch back to your code editor.

  10. In entertainment.php select and copy:

    <?php require_once('passwordProtection.php'); ?>
  11. Paste this line at the very top of each of these files in the session-start folder, saving each file after modification:

    • international.php
    • local.php
    • national.php
    • scitech.php
  12. Test the protection by navigating to any of these pages—you should be redirected to the login page every time.

  13. Click around to different pages in your browser. Notice that everything except index.php is now password-protected (click the logo to return to index.php).

  14. Switch back to your code editor and open index.php. While we don't want to password-protect the homepage, we do want it to be session-aware so it can display appropriate login/logout options. Add session awareness by inserting this code at the top:

  15. At the top of the page, add the following code:

    <?php session_start(); ?>
  16. Save the file. The report-story.php page should also be session-aware but accessible to all users.

  17. Open report-story.php from the session-start folder and add the same session_start() line at the top.

    Now all pages in our application are either fully protected or session-aware, creating a cohesive authentication system.

  18. Save the file.

Critical session_start() Requirements

The session_start() function must be the very first thing at the top of the page before any output. You can only run it once per page, or you'll get header errors.

Creating Password Protection

1

Create passwordProtection.php

Build a reusable include file that starts sessions and checks login status

2

Implement session check logic

Use isset() to verify loggedIN session variable exists and is true

3

Add header redirection

Redirect unauthorized users to login.php using header() function

4

Include protection on pages

Add require_once() to all pages needing authentication

Logging a User in

With our protection system in place, we need to create the mechanism that actually authenticates users and establishes their logged-in session state.

  1. Open login.php from the session-start folder.

  2. Preview the login page in your browser:

    • Mac: localhost:8888/phpclass/session-start/login.php
    • Windows: localhost/phpclass/session-start/login.php

    The form exists but lacks functionality. Let's implement the authentication logic.

  3. Switch back to your code editor and add session support to the top of login.php:

  4. Add the following at the top of the login.php page:

    <?php 
    
    session_start(); 
    
    ?>

    This enables session management for the authentication process.

  5. Configure the form to submit to itself by locating the form tag around line 25 and ensuring the action attribute points to the current page:

    <form action="login.php" method="post" name="submitStory" id="submitStory">

    Self-submitting forms simplify processing by keeping the authentication logic and display in the same file.

  6. Now we'll process submitted credentials. Add this authentication logic beneath session_start():

    <?php 
    
       session_start(); 
    
       if ( isset($_POST['username']) && isset($_POST['password']) ) {
    
       }
    
    ?>

    This condition ensures both username and password were submitted before attempting authentication. The && operator requires both conditions to be true.

  7. Add the credential validation logic inside the existing if statement:

    <?php 
    
       session_start(); 
    
       if ( isset($_POST['username']) && isset($_POST['password']) ) {
    
          if ($_POST['username'] == 'noble' && $_POST['password'] == 'noble') {
    
          }
    
       }
    
    ?>

    In production applications, you'd validate these credentials against a secure database with properly hashed passwords. For this tutorial, we're using hardcoded values for simplicity.

  8. When credentials match, establish the user's authenticated session by adding this code inside the credential check:

    if ($_POST['username'] == 'noble' && $_POST['password'] == 'noble') {
       $_SESSION['loggedIN'] = true;
    }

    This sets the session flag that our protection system recognizes as valid authentication.

  9. Save the file and test the authentication system.

  10. Navigate to the login page and enter noble for both username and password.

    • Mac: localhost:8888/phpclass/session-start/login.php
    • Windows: localhost/phpclass/session-start/login.php
  11. After submitting, you'll remain on the login page, but you're now authenticated. Verify this by navigating to any previously protected page—you should now have access.

    Let's improve the user experience by automatically redirecting authenticated users to a more useful location.

  12. Enhance the authentication flow by adding automatic redirection after successful login:

  13. In login.php, add this redirection code after setting the session variable:

    if ($_POST['password'] == 'noble' && $_POST['username'] == 'noble') {
    
        $_SESSION['loggedIN'] = true;
    
        header('Location: index.php');
    
        exit();
    
    }

    The header() function redirects to the homepage, while exit() ensures no additional code executes after the redirect.

  14. Save the page and test the improved flow. First, end your current session by quitting your browser completely.

  15. Relaunch your browser and attempt to access a protected page:

    • Mac: localhost:8888/phpclass/session-start/entertainment.php
    • Windows: localhost/phpclass/session-start/entertainment.php

    You should be redirected to login. If you're still authenticated, try a different browser or ensure your previous session ended.

  16. Log in with the noble credentials—you should be automatically redirected to the homepage.

    We can make this even more user-friendly by returning users to their originally requested page instead of always sending them to the homepage.

  17. Switch back to your code editor and open landingURL.php from the session-start folder.

    This utility captures the current page URL, which we'll store in a session variable to enable intelligent post-login redirection.

  18. Add this code to store the URL in the session:

    <?php 
    
       function currentPageURL() {
          $isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");

    Code Omitted To Save Space

    return $url;
       }
    
       $_SESSION['landingURL'] = currentPageURL();
    
    ?>

    This captures the complete URL of the page users were trying to access, storing it for later redirection.

  19. Save the page and integrate it into our protection system. Open passwordProtection.php.

  20. Add the URL capture functionality to our protection logic:

    <?php 
    
       session_start(); 
    
       if (! isset($_SESSION['loggedIN']) ) {
    
          require_once('landingURL.php');
    
          header('Location: login.php');
          exit();
    
       }
    
    ?>

    Now when unauthorized users hit a protected page, we'll remember where they wanted to go before redirecting them to login.

  21. We should also capture URLs on the homepage since users might bookmark it. Switch to index.php and add:

  22. Add the URL capture to the homepage:

    <?php 
    
       session_start(); 
    
       require_once('landingURL.php');
    
    ?>

    This ensures we capture the homepage URL as a valid destination too.

  23. Save the file and update the login redirection logic. Switch to login.php.

  24. Replace the simple homepage redirect with intelligent redirection around line 11:

    $_SESSION['loggedIN'] = true;
    
    if ( isset($_SESSION['landingURL']) ) {
       header('Location: '. $_SESSION['landingURL']);
    }
    else {
       header('Location: index.php');
    }    
    
    exit();

    This logic first checks if we captured a desired destination. If so, it redirects there; otherwise, it defaults to the homepage.

  25. Save the page and test the enhanced user experience.

  26. Quit your browser to end the current session, then relaunch and try accessing a specific protected page:

    • Mac: localhost:8888/phpclass/session-start/national.php
    • Windows: localhost/phpclass/session-start/national.php

    You should be redirected to login.

  27. Log in with noble as both username and password. You should be taken directly to the national.php page you originally requested, demonstrating the intelligent redirection system.

Form Processing Best Practice

Always check if both username and password POST variables are set using isset() before processing login attempts. This provides better security than assuming form data exists.

Login Implementation Process

1

Start session on login page

Add session_start() at the top of login.php to enable session variables

2

Configure form self-submission

Set form action to login.php so the page processes its own form data

3

Validate form submission

Check if both username and password POST variables are present

4

Authenticate credentials

Compare submitted values against stored credentials (database in production)

5

Set session and redirect

Create loggedIN session variable and redirect to appropriate page

Setting up a Login Error Message

Professional applications must handle authentication failures gracefully. Currently, incorrect credentials simply return users to a blank login form, providing no feedback about what went wrong.

  1. Switch to your code editor and open login.php. Examine the code around line 52—you'll find existing PHP that displays an $errorDisplay variable when it exists. We just need to set this variable when authentication fails.

  2. Locate the authentication logic around line 19 and add an else clause to handle failed logins:

    session_start(); 
    
    if ( isset($_POST['username']) && isset($_POST['password']) ) {
       if ($_POST['password'] == 'noble' && $_POST['username'] == 'noble') {
          $_SESSION['loggedIN'] = true;
          if ( isset($_SESSION['landingURL']) ) {
             header('Location: '. $_SESSION['landingURL']);
          }
          else {
             header('Location: index.php');
          }    
          exit();
       }
       else {
    
       }
    }

    This else block executes when credentials are submitted but don't match our expected values.

  3. Add a user-friendly error message in the else statement:

    else {           
       $errorDisplay = '<p class="error">I\'m sorry, that username or password is incorrect.</p>';
    }

    Note the escaped single quote (\') in the contraction "I'm"—this prevents PHP from interpreting it as the end of the string.

  4. Save the page and test the error handling:

    • Mac: localhost:8888/phpclass/session-start/login.php
    • Windows: localhost/phpclass/session-start/login.php
  5. Intentionally enter incorrect credentials. You should see the error message displayed clearly.

  6. Enter the correct credentials (noble/noble) to verify normal login still works properly.

Error Handling Approach

User Feedback

Display clear error messages when login attempts fail. Use predefined variables that conditionally render in the template.

Secure Messaging

Provide generic error messages that don't reveal whether username or password was incorrect. This prevents username enumeration attacks.

Displaying a Log in or Log Out Link

A polished application adapts its interface based on user state. The navigation should dynamically display either "Log In" or "Log Out" links depending on authentication status, providing clear visual feedback about the current session state.

  1. Open nav.php from the inc folder in the session-start folder.

    This navigation include file appears across the entire site. We'll implement conditional logic that displays appropriate authentication options based on session state. We'll use PHP's alternative syntax, which elegantly integrates with HTML without requiring numerous echo statements.

  2. Locate the login link around line 8 and restructure it for easier PHP integration:

  3. Reformat the login link with proper spacing:

    <li id="login">
    
        <a href="login.php">Log In</a>
    
    </li>

    This spacing makes it easier to wrap PHP conditional logic around the HTML elements.

  4. Implement the conditional logic structure using PHP's alternative syntax:

    <li id="login">
       <?php if ():?>
          <a href="login.php">Log In</a>
       <?php else:?>
       <?php endif?>
    </li>

    This alternative syntax (if():, else:, endif) provides cleaner separation between PHP logic and HTML markup compared to traditional brace syntax.

  5. Add the logout option in the else section:

    <li id="login">
       <?php if ():?>
          <a href="login.php">Log In</a>
       <?php else:?>
          <a href="logout.php">Log Out</a>
       <?php endif?>
    </li>
  6. Complete the conditional logic by adding the session state check:

    <?php if ( !isset($_SESSION['loggedIN']) || $_SESSION['loggedIN'] == false ):?>
       <a href="login.php">Log In</a>
     <?php else:?>
       <a href="logout.php">Log Out</a>
     <?php endif?>

    This condition checks two scenarios: either the session variable doesn't exist (user never logged in) or it's explicitly set to false (user logged out). The || operator means "or"—if either condition is true, show the login link.

  7. Save the page and test the dynamic navigation:

    • Mac: localhost:8888/phpclass/session-start/index.php
    • Windows: localhost/phpclass/session-start/index.php

    The navigation should now intelligently display "Log In" or "Log Out" based on your current authentication status, providing users with clear visual feedback and appropriate actions for their session state.

Alternative PHP Syntax for Templates

Use if(): else: endif syntax when mixing HTML and PHP extensively. This eliminates endless echo statements and makes templates more readable than traditional curly brace syntax.

Navigation State Management

FeatureLogged OutLogged In
Navigation LinkLog InLog Out
Session Check!isset($_SESSION['loggedIN'])$_SESSION['loggedIN'] == true
Target Pagelogin.phplogout.php
User AccessPublic pages onlyAll protected content
Recommended: Use conditional navigation to provide appropriate user actions based on authentication state

Key Takeaways

1PHP sessions solve the stateless nature of HTTP by maintaining user data across pages for individual users until logout or browser closure
2The session_start() function must be called before any output and only once per page to avoid header errors
3Password protection works by checking session variables and redirecting unauthorized users to login pages using header() function
4Proper form validation requires checking if POST variables exist using isset() before processing login attempts
5Session variables like $_SESSION['loggedIN'] control access throughout the application by storing authentication state
6Error handling should provide user feedback while maintaining security by not revealing specific credential validation failures
7Conditional navigation displays appropriate login or logout links based on current session authentication status
8Secure logout requires setting session variables to false, clearing the session array, and destroying the session completely

RELATED ARTICLES