Click here to Skip to main content
11,929,675 members (48,855 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


10 bookmarked

Creating a Log-in Session in PHP

, 22 Feb 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
A simple log-in system


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

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;    
        } 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') {
      $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') {
      $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
        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.



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


About the Author

Lộc Nguyễn
Software Developer
United States United States
currentJob = new ComputerScientist("ND-1550", "02/04", "SPAWAR SSC PAC");

while (live) {
try {
} catch (Exception ex) {

You may also be interested in...

Comments and Discussions

Questionhelp Pin
Member 1214037115-Nov-15 0:31
memberMember 1214037115-Nov-15 0:31 
AnswerRe: help Pin
Lộc Nguyễn17-Nov-15 14:18
professionalLộc Nguyễn17-Nov-15 14:18 
QuestionProblem in starting session -reg Pin
Member 1122965112-Nov-14 20:12
memberMember 1122965112-Nov-14 20:12 
AnswerRe: Problem in starting session -reg Pin
Lộc Nguyễn2-Sep-15 20:17
professionalLộc Nguyễn2-Sep-15 20:17 
QuestionThanks Pin
sudeep_dk27-Apr-14 7:16
membersudeep_dk27-Apr-14 7:16 
QuestionMessage Removed Pin
Lộc Nguyễn3-Apr-14 9:52
memberLộc Nguyễn3-Apr-14 9:52 
Questionerror while downloading source Pin
Krupal518-Mar-14 3:44
memberKrupal518-Mar-14 3:44 
AnswerRe: error while downloading source Pin
Piotr “Tobiasz” Kozłowski2-Apr-14 6:47
memberPiotr “Tobiasz” Kozłowski2-Apr-14 6:47 
GeneralRe: error while downloading source Pin
Lộc Nguyễn3-Apr-14 9:53
memberLộc Nguyễn3-Apr-14 9:53 
GeneralCool Pin
Killzone DeathMan28-Feb-14 7:02
groupKillzone DeathMan28-Feb-14 7:02 
Questionfile not found Pin
oorja25-Feb-14 19:11
memberoorja25-Feb-14 19:11 
AnswerRe: file not found Pin
Lộc Nguyễn3-Apr-14 9:54
memberLộc Nguyễn3-Apr-14 9:54 
GeneralMy vote of 4 Pin
FatalError0x4c22-Feb-14 20:46
memberFatalError0x4c22-Feb-14 20:46 
GeneralRe: My vote of 4 Pin
Patrick-Et. B.23-Feb-14 2:08
professionalPatrick-Et. B.23-Feb-14 2: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.

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