Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Creating a Log-in Session in PHP

, 22 Feb 2014
Rate this:
Please Sign up or sign in to vote.
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:
    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:

    // 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:
    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:

    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.
    // 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)

Share

About the Author

Lộc Nguyễn
Software Developer SPAWAR Pacific
United States United States
Currently a senior CS at University of Missouri, St. Louis (UMSL).
I do freelancing in PHP, Web, C# .NET, and Java.
 
Upon graduation in December this year (2014), I will work as a Computer Scientist at SPAWAR San Diego, CA. I am excited about that.
Follow on   Google+

Comments and Discussions

 
QuestionThanks Pinmembersudeep_dk27-Apr-14 6:16 
QuestionDemo download PinmemberLộc Nguyễn3-Apr-14 8:52 
Questionerror while downloading source PinmemberKrupal518-Mar-14 2:44 
AnswerRe: error while downloading source PinmemberPiotr “Tobiasz” Kozłowski2-Apr-14 5:47 
GeneralRe: error while downloading source PinmemberLộc Nguyễn3-Apr-14 8:53 
GeneralCool PingroupKillzone DeathMan28-Feb-14 6:02 
Questionfile not found Pinmemberoorja25-Feb-14 18:11 
AnswerRe: file not found PinmemberLộc Nguyễn3-Apr-14 8:54 
GeneralMy vote of 4 PinmemberFatalError0x4c22-Feb-14 19:46 
GeneralRe: My vote of 4 PinprofessionalPatrick-Et. B.23-Feb-14 1:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140921.1 | Last Updated 22 Feb 2014
Article Copyright 2014 by Lộc Nguyễn
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid