Sessions: Free PHP & MySQL Tutorial

Learn to build a simple login/logout application with this PHP & MySQL tutorial, starting with covering essential topics such as how to use session variables, starting a session, and destroying session variables. The guide includes step-by-step instructions on how to password-protect certain pages and how to allow users to log in.

This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Topics covered in this PHP & MySQL tutorial:

Starting a session, Using session variables, Log in/log out, Destroying session variables

Exercise Overview

The WWW is a stateless medium, meaning that one page does not “remember” or have any knowledge of another page. A variable you create on one page will not exist if you go to another page. The way around this problem is to use session variables. When you create a session variable it will be remembered across your application but only for a single user. This is useful in many situations, such as logging in a user and remembering them for that session (typically until they log out or quit the browser). Sessions can also be used to store shopping cart information, for example.

In this exercise we will create a simple login/logout application where we make a few pages password-protected.

SQL Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

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 fake little news site, with a login form that doesn’t yet do anything. What we’ll do is password-protect all the pages except the index page and make it so a user can log in and log out.

Password-Protecting Some Pages

The first thing to do is make an include that will check to see if the session has started, and if the user is logged in. If the user is NOT logged in we will display the login page.

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

  2. In order to access session variables you must use the function session_start(). It is very important to note a few things about session_start():

    • 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.
  3. In passwordProtection.php add the following bold code:

    <?php 
    
       session_start(); 
    
    ?>
    

    Easy, this starts the session!

  4. Next we’ll check to see if the user is logged in. For our application we’ll make a session variable called loggedIN. If loggedIN is set to true then the user is logged in. If it is false, or does not exist at all, then they are NOT logged in. Add the following bold code:

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

    This says that if the session variable loggedIN is NOT set, switch to the login page and stop processing the script.

    The header() function sends raw header information directly to the browser. If we include “Location:” in the header() it will relocate to whatever page we tell it to.

  5. Save the page.

  6. Now we’ll add it to a page and try it out. Open entertainment.php from the session-start folder.

  7. At the very top of the page make a new line and add the following bold code:

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

    This includes the page we just made.

  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 redirected to the login page.

  9. Let’s lock down all of our other pages (except for index.php). Switch back to your code editor.

  10. In entertainment.php select:

    <?php require_once('passwordProtection.php'); ?>
    
  11. Copy it.

  12. Paste it at the top of the following pages (all found in the session-start folder). Make sure to save each of the files:

    • international.php
    • local.php
    • national.php
    • scitech.php
  13. 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
  14. Click around to the different pages. You’ll see that everything except the index.php page is password locked (click the logo to go to index.php).

  15. Switch back to your code editor.

  16. Switch to index.php. We would still like the index page to be aware of our session, but we don’t want it to be password locked. To make it aware of the session, we just need to add session_start() at the top of the page.

  17. At the top of the page, add the following bold code:

    <?php session_start(); ?>
    
  18. Save the file.

    report-story.php should also be aware of the session, but not password protected.

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

    This way all of our pages are either password protected, or at least aware of the session.

  20. Save the file.

Logging a User In

Now that we’ve password protected our pages, we need a way for the user to actually log in!

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

  2. In a browser go to:

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

    We have a basic login page, but it doesn’t yet do anything.

  3. Switch back to your code editor.

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

    <?php 
    
        session_start(); 
    
    ?>
    

    This starts the session for the page.

  5. Also, we need to make sure the form action is pointed to itself (so that the page self-submits). Around line 25 find the action attribute in the form tag, and add the following bold code:

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

    Next we want to process the login information if the user has submitted the form. We only want to process the login if both the username and password are passed along (they always will be if the user submits the form, but specifically requiring both is a little more secure).

  6. At the top of the page underneath the session_start() add the following bold code:

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

    This says, if the username $_POST variable is set AND if the password $_POST variable is set, do something.

    && means “and,” so both parameters in the if statement must be true.

    If both values are submitted we must next check to see if they are the correct username and password. Normally we would check this information against a database, but for now we’ll just keep things simple and have the username and password directly on the page.

  7. Inside the if statement add another if statement:

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

    This says: If the username is noble AND if the password is also noble, then we can log in the user.

  8. Let’s actually set the user to log in. In the if statement you just wrote add:

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

    This sets the user to be “logged in.”

  9. Save the file.

  10. We now have enough to actually try it out. In a browser go to:

    • Mac: localhost:8888/phpclass/session-start/login.php
    • Windows: localhost/phpclass/session-start/login.php
  11. Enter noble for the username and password.

    For now you’re still being directed to the login form so it won’t look like you’ve been logged in, but in fact you have. To prove it, try navigating to one of the pages and you’ll be allowed in!

    Next we should make this a little more friendly for the user. One thing we can do is redirect them to the index page instead of the login screen.

  12. Switch back to your code editor.

  13. In login.php, underneath where you set the $_SESSION['loggedIN'] to true, add the following bold code:

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

    The header() function redirects us to the index page, and the exit() function makes sure the current page stops processing.

  14. Save the page.

  15. Let’s try this out. First we need to log out but because we haven’t written a log out function yet we can just end the session. The easiest way to do that is to just quit your browser.

  16. Switch to your browser.

  17. Quit your browser.

  18. Relaunch your browser and go to:

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

    You should be redirected to the login screen. If you are still logged in, try quitting the browser and previewing again, or launch a different browser (sometimes browsers do not end the session when they quit, although they should).

  19. Now log in again (with the noble username and password) and you will be redirected to index.php.

    Hmmm, wouldn’t it be nice if the user was redirected to the page they clicked on instead of going to the index page every time? To do this we can find the current page’s URL using the same function we used in the cookies exercise and store it in a session variable to tell the login script where to redirect.

  20. Switch back to your code editor.

  21. Open landingURL.php from the session-start folder.

    This page contains code to get the current page’s URL. We just need to save it into a session variable.

  22. Add the following bold code:

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

    Code Omitted To Save Space

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

    This saves the output of currentPageURL() into the session variable $_SESSION['landingURL']. This will allow us to use the variable again on the next page.

  23. Save the page.

  24. Now we have to include this file across our site. Open passwordProtection.php from the session-start folder.

  25. Save the file.

  26. Add the following bold code:

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

    This way if they are not logged in it will get their current page URL.

  27. We should also include it on the index.php page (because it is not password protected). Switch to index.php.

  28. Add the following bold code:

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

    Now this page will register the current page URL, too.

  29. Save the file.

  30. Switch to login.php.

  31. Instead of redirecting to the index.php page, we will redirect to the session variable we set earlier. Around line 11 find header('Location: index.php') and replace it with the following bold code:

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

    This way they are directed to the current page URL if it is defined, or directed to the index.php if it is not defined.

  32. Save the page.

  33. OK, let’s try this out. Switch to your browser.

  34. Quit your browser to end the current session.

  35. Relaunch your browser and go to:

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

    You should be taken to the login screen.

  36. Log in using noble as both username and password and you should be taken to national.php.

Setting Up a Login Error Message

What if the user types in the password incorrectly? Right now they are just taken back to the login screen. We should display a message saying that the username or password they typed in is incorrect.

  1. Switch to your code editor.

  2. Switch to login.php if you aren’t there already. Look around line 52 and you’ll see that we’ve already set up a bit of PHP that will display a variable $errorDisplay if it exists. All we need to do is set this variable if the user is NOT logged in correctly.

  3. Around line 19 find the first closing bracket and add an empty else statement. It should look as shown in bold below:

    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 {
    
       }
    }
    

    Be sure the else statement is in this location! It will be triggered if the username or password is incorrect.

  4. In the else statement add the following bold code:

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

    This adds a bit of HTML code to the $errorDisplay variable. Notice also that we escape the single quote in I’m with a \'

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

    • Mac: localhost:8888/phpclass/session-start/login.php
    • Windows: localhost/phpclass/session-start/login.php
  6. Purposefully enter the wrong username or password. You should see your error message.

  7. Enter in the correct username or password. You’ll be logged in.

Displaying a Log In or Log Out Link

Now that we can log in we need a way to log out. The navbar should also indicate that the user is logged in. Currently the navbar has a link that says Log In. When the user is logged in this should switch to Log Out. Let’s set this aspect up first.

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

    This page is an include that displays the navigation for the site. We will write a simple if/else statement that tests whether the user is logged in. If the user is NOT logged in, the nav will display a link that allows them to log in. If the user is already logged in, then nav will display a link that lets them log out.

    Because this page already has a lot of HTML code, we’ll use an alternative syntax for the if/else statement that makes it easier to mix HTML and PHP.

  2. Around line 8 find the <a> that links to login.php.

  3. Add some returns so the entire <a> tag is on its own line with extra spaces around it, separate from the <li> as shown below:

    <li id="login">
    
        <a href="login.php">Log In</a>
    
    </li>
    
  4. Next we want to wrap the if/else statement around this. First we’ll put in an empty if/else and then add the logic to the if. Add the following bold code:

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

    This alternative syntax makes it easy to mix HTML with PHP code. No more endless echo statements!

  5. In between the else and endif add a link to the logout page:

    <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. The logic for the if statement still needs to be written. It should be if the $_SESSION['loggedIN'] variable is NOT set, or if it is set to false, then display the login page. In the parentheses of the if statement, add the bold code:

    <?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?>
    
  7. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/session-start/national.php
    • Windows: localhost/phpclass/session-start/national.php
  8. If you are logged in, there should be a link to log out.

  9. Quit the browser.

  10. Relaunch your browser and go to:

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

    You should see a link to log in.

Making a Log Out Function

Finally we can write a function to log out the user. We’ve pre-made a page that will display a message to the user saying they are logged out, but currently it does not actually log the user out. Let’s write the logic that actually logs them out.

  1. Switch back to your code editor.

  2. Open logout.php from the session-start folder.

  3. At the top of the page add:

    <?php
    
       session_start();
    
       $_SESSION['loggedIN'] = false;
    
    ?>
    

    Technically this is all you need to log out the user (remember we have to start the session any time we want to use session variables)! However, for safety’s sake, it is best to set the session array to an empty array and then destroy the session.

  4. Add the following bold code:

    <?php
    
       session_start();
    
       $_SESSION['loggedIN'] = false;
    
       $_SESSION = array();
    
       session_destroy();
    
    ?>
    

    This is a good security precaution to take whenever ending a session. In this case we don’t have any valuable information stored in the session, but potentially the session could contain a user’s contact or credit card info.

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

    • Mac: localhost:8888/phpclass/session-start/logout.php
    • Windows: localhost/phpclass/session-start/logout.php
  6. You’ll be logged out. Click around and try logging in/out. Everything should work fine. Yippie!

  7. Switch back to your code editor.

  8. Close any open files. We’re done for now.

How to Learn Full-Stack Web Development

Master full-stack web development with hands-on training. Build fully functional websites and applications using HTML, CSS, JavaScript, Python, and web developer tools.

Yelp Facebook LinkedIn YouTube Twitter Instagram