Hi Guys,

Can you give me an idea how to secure a login page after logout wherein when I click the back button of the browser it will not redirect the page in the last page viewed, I read a lot of thread and saying that its all about session, can you give me a piece of code to start with?

Many thanks for the help

U can use this fragment [It works for me];

<?php

session_start(); // First initialize the current session

session_destroy(); // Then destroy the session  

header('Location: index.php'); // redirect the user to the index page 

?>

When user clicks on logout link it takes him to the logout script that has the code that Webville312 suggested in his post. The script does not do anything visual. It just destroys the session and redirects to the index page. We are assuming here that you keep the login information in the session. For really secure logout I would add a couple of statements, which just show what a vigilant person I am:

<?php

session_start(); // First initialize the current session

$_SESSION = array(); // initializes the session array to an empty array

unset($_SESSION); // unset the session array

session_destroy(); // Then destroy the session  

header('Location: index.php'); // redirect the user to the index page 

exit(); // terminate the script

?>

Good Day

I tried both of the codes but it doesnt work for me, is there anycode that I need to put on index.php?

Post the latest version of the code you have.

here is the mainlogin(main_login.php)

<?php
session_start();
include('phpconfig.php');
?>
<head>
<script language="javascript">
<!--
function checkfields (form){
    if (form.myusername.value == "") {
        alert ("Please enter your user id.");
        form.txtUserid.focus ();
        return false;
    } else if (form.mypassword.value == "") {
        alert ("Please enter your password.");
        form.txtUserpass.focus ();
        return false;
    } else {
        //form.submit ();
        return true;
    }
}
-->
</script>
</head>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form" method="post" onSubmit="return checkfields(this)" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

here is the main.html upon validation of login

<?php

// Check if session is not registered, redirect back to main page.
// Put this code in first line of web page.

if(!session_is_registered(myusername)){
header("location:main_login.php");
$check = $_POST['myusername'];
session_start();
}

?>
<html>
    <head>
        <style>
            a {font-weight: bold;}


        </style>
    </head>
<body>


<div id="container" style="width:1000px">

<div id="header" style="background-color:#FFA500;">
<h1 style="margin-bottom:0;">PPIC Inventory System</h1>
</div>

<div id="menu" style="background-color:#FFD700;height:400px;width:200px;float:left;font-family: arial;">
<a href="additem.html" target="iframe1">New Item</a><br>
<a href="rec_type.php" target="iframe1">Receiving</a><br>
<a href="iss_type.php" target="iframe1">Movement</a><br>
<a href="stocksview.php" target="iframe1">Stocks View</a><br>
<a href="qry_rcvd_type.php" target="iframe1">Received View</a><br>
<a href = "logout.php">Logout</a>
</div>

<div id="content" style="background-color:#EEEEEE;height:400px;width:800px;float:left;">

<iframe src="welcome.html" frameborder="0" width="800" height="400" name="iframe1">
</iframe>
</div>

<div id="footer" style="background-color:#FFA500;clear:both;text-align:center;">
NXP IS Team 2013</div>

</div>

</body>
</html>

here is the logout.php

<?php
    session_start();
    // this would destroy the session variables 
    $_SESSION = array(); // initializes the session array to an empty array
    unset($_SESSION); // unset the session array


    session_destroy();
    header('location:main_login.php');
    exit(); // terminate the script
?>

Please post also the checklogin.php code which is where you are supposed to check credentials and set up the session and phpconfig.php (and remove any sensitive data from it!!).

Here is the checklogin.php

<?php

$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="mysys"; // Database name
$tbl_name="tblusers"; // Table name
$encoder = "encoder";
$administrator = "administrator";
session_start();
//include 'functions.php';
//sec_session_start(); // Our custom secure way of starting a php session. 

$today = date('Y-m-d');

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$now = date('Y-m-d');
$sql="SELECT  * FROM $tbl_name WHERE user_id='$myusername' and dateExp > '$now' ";

$result=mysql_query($sql);
$expDate = strtotime(date("Y-m-d", strtotime($info['dateReg'])) . " + 30 days");
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row

if($count == 1  ){
                    //start session
                    session_start();
                    //end of start session
                $sql2= "SELECT  * FROM $tbl_name WHERE user_id='$myusername' and user_password='$mypassword' and user_level = '$administrator' ";
                $result2=mysql_query($sql2);


                $count2=mysql_num_rows($result2);
                if($count2==1 ){

                                    //$_SESSION['ip'] = UserIP();
                                    //$_SESSION['userid'] = $row['user_id'];
                                    //$_SESSION['fullname'] = $row['user_fname']." ".$row['user_lname'];
                                    //$_SESSION['userlevel'] = $row['user_level'];
                                    //$_SESSION['lastaccess'] = date("Y-m-d h:i:s A");

                                    session_register("myusername");
                                    session_register("mypassword");

                                    session_register("");
                                    header("location:main.html");
                                    session_destroy();
                                }
                //else
                    //{
                    //  header("location:main_login2.php");
                    //}

        //{// Register $myusername, $mypassword and redirect to file "login_success.php"
        else if($count == 1  ){
                $sql2= "SELECT  * FROM $tbl_name WHERE user_id='$myusername' and user_password='$mypassword' and user_level = '$encoder' ";
                $result2=mysql_query($sql2);


                $count=mysql_num_rows($result2);
                if($count==1 ){
                                    session_start();
                                    session_register("myusername");
                                    session_register("mypassword");

                                    session_register("");
                                    header("location:mainEncoder.html");
                                }


                else
                    {
                        header("location:main_login2.php");
                    }

        //{// Register $myusername, $mypassword and redirect to file "login_success.php"

}



}


else {
         if($count == 0)
                        {
                            header("location:mainlogin3.html");
                        }
        else{session_register("");
        header("location:register2.php");
        }

    }
?>

there's nothing much on the phpconfig.php, I was just trying something else there :)

The checklogin.php is the page where you set up the session if login is successful. There are some issues on that page:

Do not use session_register function since it is already deprecated. See warning on http://php.net/manual/en/function.session-register.php: This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Use assignments to $_SESSION array as already in your code but commented out:

$_SESSION['ip'] = UserIP();
$_SESSION['userid'] = $row['user_id'];
$_SESSION['fullname'] = $row['user_fname']." ".$row['user_lname'];
$_SESSION['userlevel'] = $row['user_level'];
$_SESSION['lastaccess'] = date("Y-m-d h:i:s A");

In the code you have some nested if and elseif conditions which has the following structure:

if($count == 1) {
    if($count2==1) {
    } else if($count == 1) {
        if($count==1) {
        } else {
        }
    }
} else {
    if($count == 0) {
    } else {
    }
}

Within the first block you check if $count == 1 three times which is unnecessary (you should do it only at top level). Please check if this is what you meant or is that an error.

This is enough for this post I will send you another one when I finish testing. Meanwhile please look at the code considering above notes.

This is my version of the login script which is simplified, removing duplicate checks and queries and still does the same. See the comments in the code.

<?php
//start session on the beginning of the script
session_start();

$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="mysys"; // Database name
$tbl_name="tblusers"; // Table name
$encoder = "encoder";
$administrator = "administrator";
session_start();
//include 'functions.php';
//sec_session_start(); // Our custom secure way of starting a php session. 

$today = date('Y-m-d');

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$now = date('Y-m-d');

$expDate = strtotime(date("Y-m-d", strtotime($info['dateReg'])) . " + 30 days");

// read all the data about the user in one query
$sql="SELECT  * FROM $tbl_name WHERE user_id='$myusername' AND user_password='$mypassword' AND dateExp > '$now' ";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// if result matched $myusername and $mypassword, table row must be 1 row
// this is when user was found
if($count == 1) {

    // assign all the data to the session variables
    // session variables that differ for each user level can be set
    // within the switch statement below
    $_SESSION['ip'] = UserIP();
    $_SESSION['userid'] = $row['user_id'];
    $_SESSION['fullname'] = $row['user_fname']." ".$row['user_lname'];
    $_SESSION['userlevel'] = $row['user_level'];
    $_SESSION['lastaccess'] = date("Y-m-d h:i:s A");

    // determine the user level
    $user_level = $row['user_level'];

    // redirect to appropriate pages based on user level
    // please note: redirect to PHP pages so you can use session variables!!!
    switch($user_level) {

        case $administrator:
            // redirect to the administrator page
            header("location:someadminpage.php"); 
            exit();
            break;

        case $encoder:
            // redirect to the encoder page
            header("location:someencoderpage.php"); 
            exit();
            break;

        default:
            // if none of the allowed user levels are found
            // redirect to the page that unsets the session and redirects to login page
            header('location:logout.php'); 
            exit();
            break;
    }

// this is when user not found (wrong username or password or expired) 
} else {

    // redirect to the page that unsets the session and redirects to login page
    header('location:logout.php');
}
?>

And this is how you start each script for logged-in user. It has to be a PHP script not a html page.

// start the session
session_start();

// on each page first do the checks if login is OK nad user has access rights
// (you can add other conditions here if needed)
// if login not OK ot user hasn't got access rights, redirect to the logout script
// this is an example for the administrator
if(!isset($_SESSION['user_level']) || $_SESSION['user_level'] != 'administrator') {

    // redirect to the page that unsets the session and redirects to login page
    header('location:logout.php');
}

// now carry on with the code for logged in user
...

The code for the logout.php page is the one from the above post.

Good Day Broj1

I tried the code but it seems that the case statement doesnt work, still no success on the program, by the way what you mean php script not html page?do you mean that eventhough it's a html code but I will save it as .php?is it right?

Thanks for the patience sir :)

I tried the code but it seems that the case statement doesnt work, still no success on the program

Can you describe what does not work.

by the way what you mean php script not html page?do you mean that eventhough it's a html code but I will save it as .php?

Yes. And each page will have some code in it. At least the piece of code from my last post above to check the existence of session variables and user access level. Without this code nothing will work.

// start the session
session_start();

// on each page first do the checks if login is OK nad user has access rights
// (you can add other conditions here if needed)
// if login not OK ot user hasn't got access rights, redirect to the logout script
// this is an example for the administrator
if(!isset($_SESSION['user_level']) || $_SESSION['user_level'] != 'administrator') {

    // redirect to the page that unsets the session and redirects to login page
    header('location:logout.php');
}

// now carry on with the code for logged in user
...

I test the code, but it only works in case default, none of case $administrator or case $encoder are working, because I use a testpage to redirect upon satisfying the case statement, but all goes to case default only

Here is the default_login.php

<?php
session_start();
include('phpconfig.php');


?>
<head>
<script language="javascript">
<!--
function checkfields (form){
    if (form.myusername.value == "") {
        alert ("Please enter your user id.");
        form.txtUserid.focus ();
        return false;
    } else if (form.mypassword.value == "") {
        alert ("Please enter your password.");
        form.txtUserpass.focus ();
        return false;
    } else {
        //form.submit ();
        return true;
    }
}
-->
</script>
</head>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form" method="post" onSubmit="return checkfields(this)" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

Here is now the checklogin.php which you suggested

  <?php
    //start session on the beginning of the script
    session_start();
    $host="localhost"; // Host name
    $username="root"; // Mysql username
    $password=""; // Mysql password
    $db_name="mysys"; // Database name
    $tbl_name="tblusers"; // Table name
    $encoder = "encoder";
    $administrator = "administrator";
 //   session_start();
    //include 'functions.php';
    //sec_session_start(); // Our custom secure way of starting a php session.
    $today = date('Y-m-d');
    // Connect to server and select databse.
    mysql_connect("$host", "$username", "$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");
    // username and password sent from form
    $myusername=$_POST['myusername'];
    $mypassword=$_POST['mypassword'];
    // To protect MySQL injection (more detail about MySQL injection)
    $myusername = stripslashes($myusername);
    $mypassword = stripslashes($mypassword);
    $myusername = mysql_real_escape_string($myusername);
    $mypassword = mysql_real_escape_string($mypassword);
    $now = date('Y-m-d');
    $expDate = strtotime(date("Y-m-d", strtotime($info['dateReg'])) . " + 30 days");
    // read all the data about the user in one query
    $sql="SELECT * FROM $tbl_name WHERE user_id='$myusername' AND user_password='$mypassword' AND dateExp > '$now' ";
    $result=mysql_query($sql);
    // Mysql_num_row is counting table row
    $count=mysql_num_rows($result);
    // if result matched $myusername and $mypassword, table row must be 1 row
    // this is when user was found
    if($count == 1) {
    // assign all the data to the session variables
    // session variables that differ for each user level can be set
    // within the switch statement below
    //$_SESSION['ip'] = UserIP();
    $_SESSION['userid'] = $row['user_id'];
    $_SESSION['fullname'] = $row['user_fname']." ".$row['user_lname'];
    $_SESSION['userlevel'] = $row['user_level'];
    //$_SESSION['lastaccess'] = date("Y-m-d h:i:s A");
    // determine the user level
    $user_level = $row['user_level'];
    //$user_level = $_SESSION['userlevel'];
    // redirect to appropriate pages based on user level
    // please note: redirect to PHP pages so you can use session variables!!!
    switch($user_level) {
    case $administrator:
    // redirect to the administrator page
    header("location:main.php");
    exit();
    break;
    case $encoder:
    // redirect to the encoder page
    header("location:mainEncoder.php");
    exit();
    break;
    default:
    // if none of the allowed user levels are found
    // redirect to the page that unsets the session and redirects to login page
    header('location:main.php');
    exit();
    break;
    }
    // this is when user not found (wrong username or password or expired)
    } else {
    // redirect to the page that unsets the session and redirects to login page
    header('location:logout.php');
    }
    ?>

Here is the main.php for administrator

<?php

// Check if session is not registered, redirect back to main page.
// Put this code in first line of web page.
session_start();


if(!isset($_SESSION['user_level']) || $_SESSION['user_level'] != 'administrator') {
// redirect to the page that unsets the session and redirects to login page
header('location:logout.php');
}


?>
<html>
    <head>
        <style>
            a {font-weight: bold;}


        </style>
    </head>
<body>


<div id="container" style="width:1000px">

<div id="header" style="background-color:#FFA500;">
<h1 style="margin-bottom:0;">PPIC Inventory System</h1>
</div>

<div id="menu" style="background-color:#FFD700;height:400px;width:200px;float:left;font-family: arial;">
<a href="additem.html" target="iframe1">New Item</a><br>
<a href="rec_type.php" target="iframe1">Receiving</a><br>
<a href="iss_type.php" target="iframe1">Movement</a><br>
<a href="stocksview.php" target="iframe1">Stocks View</a><br>
<a href="qry_rcvd_type.php" target="iframe1">Received View</a><br>
<a href = "logout.php">Logout</a>
</div>

<div id="content" style="background-color:#EEEEEE;height:400px;width:800px;float:left;">

<iframe src="welcome.html" frameborder="0" width="800" height="400" name="iframe1">
</iframe>
</div>

<div id="footer" style="background-color:#FFA500;clear:both;text-align:center;">
NXP IS Team 2013</div>

</div>

</body>
</html>

and here is the logout.php

<?php
    session_start();
    // this would destroy the session variables 
    $_SESSION = array(); // initializes the session array to an empty array
    unset($_SESSION); // unset the session array


    session_destroy();
    header('location:main_login.php');
    exit(); // terminate the script
    */
?>

can you figure out whats wrong?thank you for the support sir

In checklogin.php on line 42 you assign a sesion variable the value read from the database:

$_SESSION['userlevel'] = $row['user_level'];

In main.php on line 8 you check for existence and value of session variable:

if(!isset($_SESSION['user_level']) || $_SESSION['user_level'] != 'administrator') {

The trouble is the indexes of the session variable are different. Once you use userlevel and another time you use user_level so the condition is true and you get redirected to the login page. The error might also originate from my examples since I do not know all the code. I strongly suggest that you use the same indexes for $row arrays, $_SESSION, $_POST and $_GET variables, and they should be same as the database column name. Otherwise you will get confused and errors like this will happen. The following is just an example:

Column name in the DB table: user_level
$row value for this column: $row['user_level']
a temporary variable: $user_level
$_SESSION variable: $_SESSION['user_level']
$_POST / $_GET variables: $_POST['user_level'] / $_GET['user_level']

As you see above you allways know that you are referring to user_level. Please correct the code as per above suggestion and test it. If it does not work, please post the code (the latest version). Sory to get you to post your code that many times, but it is the only way to go.

Hi Broj1

I change all and make it uniform to user_level, still no progress, please help I'm having a hard time with this.

Thank you for the continuous support :)

Looking at your last version of the checklogin.php page you redirect administrator to main.php and user with no access (case: default) to the main.php page. Can you please clearly state what are names for the administrator page, encoder page and login page.

main.php is the page for the administrator, mainEncoder.php is the page for the encoder, and main_login.php is the index where the user will input its username and password

OK, we will have to do this in steps. First change the default redirection to logout.php. Then add some debug code in switch statement and login as administrator, encoder and nonexisting user. Please post the output for each login attempt.

switch($user_level) {

    case $administrator:

        // DEBUG
        die('REDIRECTING TO main.php');

        // redirect to the administrator page      
        header("location:main.php");
        exit();
        break;

    case $encoder:

        // DEBUG
        die('REDIRECTING TO mainEncoder.php');

        // redirect to the encoder page
        header("location:mainEncoder.php");
        exit();
        break;

    default:

        // DEBUG
        die('REDIRECTING TO logout.php');

        // if none of the allowed user levels are found
        // redirect to the page that unsets the session and redirects to logout page
        header('location:logout.php');
        exit();
        break;
}

what do you mean add some debug code? Is there additional code that I need to put on the comment //add some debug code?

No. In my previous post I have put a debug code in each case statement. This way I can check which case statement gets executed. So please šut this same code in your script and check whether the switch is redirecting to appropriate pages. If yes we have to look for errors on redirected pages. If no, we have to see where the error occured before redirection.

Hi broj1,

I figure out whats the problem, thanks for the support man, your code has been a great help to me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.