Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PHP

Creating a Log-in Session in PHP

4.60/5 (5 votes)
22 Feb 2014CPOL2 min read 127.1K   5.5K  
A simple log-in system

Introduction

This article is based on a project I'm currently working on: todaythoughts.com

Most database driven web applications need a log-in system to allow certain users to modify data. Session is the most common way.

Setup the Project Folder

Usually, I orgainize a project as above.
Most of the pages contain the same three elements (header, sidebar, and footer). So each page can include these three.

Get User Input

Home page (index.php) would be the first to create. It has a link to login.php page. From this login.php page, there is a form to get username and password, usually a form with POST method to submit user input to the server. In the real-world, the page will compare these against user information from the database. But in this tip, a username and password were assumed:

Here are some important points:

  1. In order to use session, we have to start it at the very top of the page.
  2. When the user input is correct, we want to direct the user to a destinated page.
    PHP header() function is used for that purpose. But the problem that happens quite often is header() doesn't work if there were already output (even a newline or a space). That is why ob_start() and ob_end_flush() are used to buffer output. ob_start() should be placed at the very beginning and ob_end_flush() at the end (footer.php is a good place).

Plan of Attack

  1. Three global variables are kept track of:
    • $_SESSION['valid'] to determine if the current session is valid or not
    • $_SESSION['timeout'] to keep track of how long user has logged in
    • $_SESSION['username'] in case needed
  2. redirect.php is the central place to process all redirectings. For example:
    PHP
    if ($_GET['action'] == 'succeed') {
      $msg = 'Logged successfully...';
      echo '
    ' . $msg . '
    ';
      header('Refresh: 2; URL=index.php');
    }

    After logging in successfully, redirect.php waits 2 seconds and redirects user to the home page.

    Homepage has the logic to differentiate if a session if valid based on several factors:

    PHP
    // implemented in header.php
     $inactive) {
            $_SESSION['valid'] = false;    
            session_unset();
            session_destroy();
        } else {
            echo $_SESSION['username'];
            echo '<a href="redirect.php?action=logout">Logout';
        }
        } else {
            echo '<a href="login.php">Login</a>';
        }
    ?>

    Here, there are two cases when the session becomes invalid:

    • When the time is over.
    • When the user clicks log-out link.

    --> In either case, we will set clear all global session variables and destroy that session (sometimes not necessary).

  3. Here again, redirect.php is to do its job where the user logs out:
    PHP
    else if ($_GET['action'] == 'logout') {
      session_unset();
      session_destroy();
      $msg = 'Logged out. Now come back to homepage';
      echo '
    ' . $msg . '
    ';
      header('Refresh: 2; URL=index.php');
    }

    Or when the time is over:

    PHP
    else if ($_GET['action'] == 'timeover') {
      session_unset();
      session_destroy();
      $msg = 'Inactivity so long, now sign-in again.';
      echo '
    ' . $msg . '
    ';
      header('Refresh: 2; URL=login.php');
    } 
  4. Now, we are able to determine if the session is valid or not. If not, the user is not allowed to access a certain area, such as update.php to make some modifications to the data stored in the database, for example.
    PHP
    // update.php
    <?php
        if (!isset($_SESSION['valid'])) {
            header('Location: redirect.php?action=invalid_permission');    
        } 
    ?>

    In this case, we redirect user to the redirecting center to determine what to do.

  5. If the session is valid, the user can continue working on update.php.

END

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)