0

Im using The PHP-LOGIN project (minimal) but I can't understand how to set the timeout for session. This is my login file:

<?php

/**
 * Class login
 * handles the user's login and logout process
 */
class Login
{

    /**
     * @var object The database connection
     */
    private $db_connection = null;

    /**
     * @var array Collection of error messages
     */
    public $errors = array();

    /**
     * @var array Collection of success / neutral messages
     */
    public $messages = array();

    /**
     * the function "__construct()" automatically starts whenever an object of this class is created,
     * you know, when you do "$login = new Login();"
     */
    public function __construct()
    {
        if (isset($_COOKIE[session_name()]))
        {
            session_start();
            // check the possible login actions:
            // if user tried to log out (happen when user clicks logout button)
            if (isset($_GET["logout"]))
            {
                $this->doLogout();
            }
            // login via post data (if user just submitted a login form)
            elseif (isset($_POST["login"]))
            {
                $this->dologinWithPostData();
            }
        }
    }

    /**
     * log in with post data
     */
    private function dologinWithPostData()
    {
        // check login form contents
        if (empty($_POST['user_name']))
        {
            $this->errors[] = "Username field was empty.";
        }
        elseif (empty($_POST['user_password']))
        {
            $this->errors[] = "Password field was empty.";
        }
        elseif (!empty($_POST['user_name']) && !empty($_POST['user_password']))
        {

            // create a database connection, using the constants from config/db.php (which we loaded in index.php)
            $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

            // change character set to utf8 and check it
            if (!$this->db_connection->set_charset("utf8"))
            {
                $this->errors[] = $this->db_connection->error;
            }

            // if no connection errors (= working database connection)
            if (!$this->db_connection->connect_errno)
            {

                // escape the POST stuff
                $user_name = $this->db_connection->real_escape_string($_POST['user_name']);

                // database query, getting all the info of the selected user (allows login via email address in the
                // username field)
                $sql                   = "SELECT user_name, user_email, user_password_hash
                    FROM users
                    WHERE user_name = '" . $user_name . "' OR user_email = '" . $user_name . "';";
                $result_of_login_check = $this->db_connection->query($sql);

                // if this user exists
                if ($result_of_login_check->num_rows == 1)
                {

                    // get result row (as an object)
                    $result_row = $result_of_login_check->fetch_object();

                    // using PHP 5.5's password_verify() function to check if the provided password fits
                    // the hash of that user's password
                    if (password_verify($_POST['user_password'], $result_row->user_password_hash))
                    {

                        // write user data into PHP SESSION (a file on your server)
                        $_SESSION['user_name']         = $result_row->user_name;
                        $_SESSION['user_email']        = $result_row->user_email;
                        $_SESSION['user_login_status'] = 1;
                        header("location: index.php");
                    }
                    else
                    {
                        $this->errors[] = "Wrong password. Try again.";
                    }
                }
                else
                {
                    $this->errors[] = "This user does not exist.";
                }
            }
            else
            {
                $this->errors[] = "Database connection problem.";
            }
        }
    }

    /**
     * perform the logout
     */
    public function doLogout()
    {
        // delete the session of the user
        $_SESSION         = array();
        session_destroy();
        // return a little feeedback message
        $this->messages[] = "You have been logged out.";
    }

    /**
     * simply return the current state of the user's login
     * @return boolean user's login status
     */
    public function isUserLoggedIn()
    {
        if (isset($_SESSION['user_login_status']) AND $_SESSION['user_login_status'] == 1)
        {
            return true;
        }
        // default return
        return false;
    }

}
Michał
  • 2,456
  • 4
  • 26
  • 33
soft
  • 1

3 Answers3

0
Use session.gc_maxlifetime

Set session.gc_maxlifetime = 3600 in phi.ini for 1 hour

or

ini_set('session.gc_maxlifetime',3600); // in your script for 1 hour
user1844933
  • 3,296
  • 2
  • 25
  • 42
0
ini_set('session.gc_maxlifetime',3000);

if you want to know more in-depth Expire Session

Community
  • 1
  • 1
Tabby
  • 388
  • 1
  • 11
0

Make few modifications to your function so that you store the time whenever user visits a page after login. You can save this time as a session variable. This time will get updated each and every time the user opens a page or refreshes, so that you can keep track that users is still using the website.

In isUserLoggedIn() function you can add a condition to check time stored in session against current time before allowing the user to view the page. May be you can see if this time is not more than 30mins.

To start making this change, add $_SESSION['lastvisit']=time(); in dologinWithPostData() function below $_SESSION['user_login_status'] = 1;, so that it looks like below

  // using PHP 5.5's password_verify() function to check if the provided password fits
  // the hash of that user's password
  if (password_verify($_POST['user_password'], $result_row->user_password_hash))
  {
      // write user data into PHP SESSION (a file on your server)
      $_SESSION['user_name']         = $result_row->user_name;
      $_SESSION['user_email']        = $result_row->user_email;
      $_SESSION['user_login_status'] = 1;
      $_SESSION['lastvisit']         = time();
      header("location: index.php");
   }

and in isUserLoggedIn() function add the condition as below

public function isUserLoggedIn()
{
    $lastvisitplus30mins = $_SESSION['lastvisit']+1800; //60sec * 30min -> you can increase the time as per your requirement 
    if (isset($_SESSION['user_login_status']) AND $_SESSION['user_login_status'] == 1 AND $lastvisitplus30mins < time())
    {
        return true;
    }
    // default return
    return false;
}

Hope that helps you fix the login session

Lepanto
  • 1,413
  • 1
  • 8
  • 15