0

Currently making a small application on html, which utilises php for user login which is connected to a database. User login works as required, users can login, register, logout and relogin as a normal login behaviour should function.

However, when a user logs out, they are able to immediately 're-enter' the application by using the browser BACK button, which is an obvious security flaw.

I am trying to use sessions in creating a solution to the above issue.. any help would be highly appreciated. My application is currently broken down into the following pages.

1) login.php (simple username & password entered into a form, form executes logincheck.php

2) logincheck.php (SEE BELOW)

<?php
session_start();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="site.css">
</head>
<body>
<div class="frame">
<div class="headerf"></div>
<div class="contentf">
<h3>Incorrect user credentials.</h3>    
<?php
include("info.inc.php");
$comm=@mysql_connect(localhost,$username,$password);
$rs=@mysql_select_db($database) or die( "Unable to select database"); 

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

// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM users WHERE username='$myusername' and password='$mypassword'";
$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
if($count==1){

// Register $myusername, $mypassword and redirect to file "index.php"
$_SESSION["username"] = $myusername;
$_SESSION["password"] = $mypassword;
header("location:../index.php");
}
else {
echo "Please return to the log-in page.";
}
?>

<form name="form" method="post" action="../login.php"><br>
<td><input type="submit" name="Submit" value="Back"></td>
</div>
</div>
</body>
</html>

3) index.php (if successful login, user is redirected to this page, where they have access to the application and can navigate throughout as normal).

4) logout.php (session is ended, user is redirected to login page)

I currently have session start in the login, and session end in the logout pages. How can i implement a secure form of loggin in ? Have been trying online examples, but to no avail, i.e. http://blog.teamtreehouse.com/how-to-create-bulletproof-sessions

My ideal fix would be, instead of a user being able to 'BACK' into the application after logout, they are redirected to the login page again or username and password is prompted for again

any help is highly appreciated!

WhoKnew
  • 3
  • 2
  • Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). – Jay Blanchard Mar 15 '16 at 18:19
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Mar 15 '16 at 18:20
  • Write an `assert_logged_in()` function which checks the session. If the session variables have been properly destroyed this function will redirect them to login. – Jay Blanchard Mar 15 '16 at 18:21
  • nothing to do with sessions, really. they're just viewing cached pages in their browser. but your code SHOULD check for login status EVERY time your site's scripts are invoked. so if/when the user's browser DOES hit your server, they won't get any "logged in" data. – Marc B Mar 15 '16 at 18:24
  • Thank you for above comments, will try to interpret and read up inorder to make adjustments to my code. I checked online Marc, and it appears to be possible with sessions, i was thinking something of a php check session name, if null, the user is redirected? as a user logs out, the session is destroyed and should be NULL? comments? – WhoKnew Mar 15 '16 at 18:37

2 Answers2

0

After checking the user's credentials, if the user has a valid username and password you would set a session variable indicating they've successfully been logged in.

Example (using a snippet from your logincheck.php script):

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

    // Register $myusername, $mypassword and redirect to file "index.php"
    $_SESSION["username"] = $myusername;
    $_SESSION["password"] = $mypassword;

    // set a session variable that is checked for
    // at the beginning of any of your secure .php pages
    $_SESSION["loggedIn"] = true;

    header("location:../index.php");
}

At the very beginning of each of your secure pages check to see if this session variable has been set as a result of logging in. If the session variable is not set, then you simply re-direct the user back to your login.php page.

Example:

<?php

    // start session
        session_start();

    // check for logged in session
        if(!$_SESSION['loggedIn'])
        {
            // user is not logged in
            // re-direct user to login.php
                header("Location: login.php");
                exit;
        }

?>

As the other comments mention, I highly recommend moving to either MySQLi or PDO database functions as the mysql_* functions have been deprecated from later versions of PHP.

urlex
  • 36
  • 4
  • Hi Urlex, pretty much more or less what i was imagining was possible, thank you. will have a try now. I am unfamiliar with !$_SESSION['loggedIn'], to use this, what code do i require on my login page to identify a user as being logged in? – WhoKnew Mar 15 '16 at 18:48
  • I made some edits to my answer to hopefully help clear up some confusion. – urlex Mar 15 '16 at 19:07
  • tried the above, the code for checking session variables comes back with a page error: (serverurl) is currently unable to handle this request? tried playing around and no fix at the moment, any ideas? – WhoKnew Mar 15 '16 at 19:32
  • Perhaps your login.php file is located in a different directory? Make sure the file path to login.php is correct. Looking at your code I notice that you're re-directing to ../index.php, so I suspect your files are in different directories. (Which is fine as long as you have the right file path.) – urlex Mar 15 '16 at 19:58
  • Checked and rechecked, file locations are correct but still recieving an error, when i remove the php check session code, it works fine, so theres some sort of issue going on within those few lines of code? Atm, i have the above code before my html of the secure page, is that how it should be ? – WhoKnew Mar 15 '16 at 23:44
  • managed to get it working, merged abit of your recommendation with my own doing, basically made each page into a php loop, if user true = show html, else redirect to login page. back button does not work, as it rechecks the session and redirects to login page once again. Thank you all for assistance. – WhoKnew Mar 16 '16 at 01:02
-1

you need to register the new 'loggedIn' session variable when you retrieve the data from the database or you can also use your existing session variable ie username against the starting of each page instead of adding a new session variable to check the same....

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "index.php"
$_SESSION["username"] = $myusername;
$_SESSION["password"] = $mypassword;
$_SESSION['loggedIn'] = true;
header("location:../index.php");
}
coolstoner
  • 719
  • 2
  • 9
  • 20
  • 5 years old answer. But I stumbled upon it. For security reason it's never, NEVER a good idea to store the credentials in the session. A successful attack to the server might enable an attacker reading the sessions and steal the credentials and to log in in serveral other websites. At least using a hash is making his approach useless then. But in fact avoid storing the credentials in the session. To make a session more secure use additonal data e. g. the user agent and the IP (except minor edge cases). – codekandis Jan 07 '22 at 13:25