Click here to Skip to main content
15,881,248 members
Articles / Programming Languages / PHP
Tip/Trick

Creating a Log-in Session in PHP

Rate me:
Please Sign up or sign in to vote.
4.60/5 (5 votes)
22 Feb 2014CPOL2 min read 126.1K   5.5K   11   13
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)


Written By
Software Developer
United States United States
while (live) {
try {
learn();
code();
food();
...
} catch (Exception ex) {
recover();
}
}

Comments and Discussions

 
Questionhelp Pin
Member 1214037114-Nov-15 23:31
Member 1214037114-Nov-15 23:31 
AnswerRe: help Pin
Lộc Nguyễn17-Nov-15 13:18
professionalLộc Nguyễn17-Nov-15 13:18 
Would need more details, but general idea is: (1) Connect to MySQL using your connection string and credential (username/password), (2) issue SQL statements, such as "SELECT * FROM YourTable WHERE condition", and (3) process the result set.

Loc
QuestionProblem in starting session -reg Pin
vinoth ViZiO12-Nov-14 19:12
vinoth ViZiO12-Nov-14 19:12 
AnswerRe: Problem in starting session -reg Pin
Lộc Nguyễn2-Sep-15 19:17
professionalLộc Nguyễn2-Sep-15 19:17 
QuestionThanks Pin
sudeep_dk27-Apr-14 6:16
sudeep_dk27-Apr-14 6:16 
Questionerror while downloading source Pin
Krupal518-Mar-14 2:44
Krupal518-Mar-14 2:44 
AnswerRe: error while downloading source Pin
Piotr “Tobiasz” Kozłowski2-Apr-14 5:47
Piotr “Tobiasz” Kozłowski2-Apr-14 5:47 
GeneralRe: error while downloading source Pin
Lộc Nguyễn3-Apr-14 8:53
professionalLộc Nguyễn3-Apr-14 8:53 
GeneralCool Pin
Killzone DeathMan28-Feb-14 6:02
Killzone DeathMan28-Feb-14 6:02 
Questionfile not found Pin
oorja25-Feb-14 18:11
oorja25-Feb-14 18:11 
AnswerRe: file not found Pin
Lộc Nguyễn3-Apr-14 8:54
professionalLộc Nguyễn3-Apr-14 8:54 
GeneralMy vote of 4 Pin
fioresoft22-Feb-14 19:46
fioresoft22-Feb-14 19:46 
GeneralRe: My vote of 4 Pin
Patrick-Et. B.23-Feb-14 1:08
professionalPatrick-Et. B.23-Feb-14 1:08 

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

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