0

I am creating a small login facility. i would like it to be simple but also secure. I wanted to timeout my session after 30 minutes of inactivity. I saw a solution for this here by Gumbo. However I am unsure where to add the code to my own code... Can somebody help me ... Here is the solution which i want to add into my code (by Gumbo) and underneath that is my own login.php page:

Conclusion / best solution (from another stackoverflow post ):

The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request:

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    // last request was more than 30 minutes ago
    session_unset();     // unset $_SESSION variable for the run-time 
    session_destroy();   // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

Updating the session data with every request also changes the session file's modification date so that the session is not removed by the garbage collector prematurely.

You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:

if (!isset($_SESSION['CREATED'])) {
    $_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
    // session started more than 30 minutes ago
    session_regenerate_id(true);    // change session ID for the current session and invalidate old session ID
    $_SESSION['CREATED'] = time();  // update creation time
}

login.php

<?php
session_start();
header('Content-Type: text/html; charset=utf-8');

require("database.php");
require("phpfunctions.php");
if(isset($_POST["log_out"]) && ($_POST["log_out"] == '1')) {
    //this means we have come from another page after pressing the log out button 
    //so therefore we remove session variables and destroy session
    session_unset(); 
    session_destroy(); 
    //$log_out_message = "You have been logged out";
}

if (isset($_SESSION["username"])) {
    //if the username session variable is already set then they are already logged in so send them to the index page
    //we will perform further checks there on the validity of the session variables
    header("Location: index.php"); 
        exit();
}


    //collect the post data if the login form has been submitted
    if (isset($_POST["username"]) && isset($_POST["password"])){

        $username = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]); // filter everything but numbers and letters
        $password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]); // filter everything but numbers and letters

        //check if this username and password exist in our database and are therefore valid
        $query = "SELECT * FROM users WHERE username=:username LIMIT 1";

        $statement = $pdoConnection->prepare($query);
        $statement->bindValue(':username', $username, PDO::PARAM_STR);
        $statement->execute();
        $statement->setFetchMode(PDO::FETCH_ASSOC);
        $count = 0;
        while($row = $statement->fetch()){
            //username exists.
            if (password_verify($password, $row["hashedPassword"])) {
                //password is verified
                //store the hashedPassword into a variable.
                $dbHashedValue = $row["hashedPassword"];
                $id = $row["userID"];
                $count++;
            }

        }

        //if count is 1 that means we found matching username in our database and also have verifed the password
        if($count == 1){
            //If our login credentials are matched with the database and therefore valid we store the values into session variables.
            //$_SESSION['incorrectLogin'] = false;
            $_SESSION["userID"] = $id;
            $_SESSION["username"] = $username;
            $_SESSION["password"] = $dbHashedValue;


            //all login information is correct and we have stored it into SESSION variables so 
            //we are ready to allow the user in to our system
            header("Location: index.php");
            //exit the rest of the script

            exit();
        }else if($count == 0){
            //create generic message without giving too much information away to the user in order to be more secure.
            $incorrectLoginDetails = "Invalid Login! Please try again!";

        }

    }


?>

index.php

<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
require("database.php");
require("phpfunctions.php");
//check if the username session variable exists 
//this will exist only if the person has passed the login stage therefore we now know they are logged in
if(!isset($_SESSION['username'])){
    header('Location: login.php');
    exit();
}
//also need to check this username exists in the database and also that the session password matches up with the database.

?>
Community
  • 1
  • 1
Sarah
  • 1,943
  • 2
  • 24
  • 39

0 Answers0