Link to home
Start Free TrialLog in
Avatar of Bruno1990
Bruno1990

asked on

How to keep users logged in until they are logged out or close browser

Below I have 3 php scripts going in order from when user logs in, to their login details being stored and then the log out. Now what I am doing at the moment is that I am using `$SESSION` to determine which user is logged in and then using the session_gcmaxlife to add extra time so that the session does not expire for 12 hours. So that means the user can stay logged in for 12 hours for which after that amount of time it will log the user out automatically. This is just a very basic why of producing a login system.

But what I want to do is be able to keep the user logged in for unlimited amount of time until they have either clicked on the logout link or have closed down the browser. What my question is that with the minimum amount of code change as possible, how can the codes below be altered so that they keep a user logged in until they logout or close the browser?

Can this be done with minimum change of code, the reason I am showing 5 php scripts is so that I can see what changes needs to be made for each different script, so then I should be able to make changes for other scripts within an application.

Can you please show a sample code so I can see how and where to make the changes please. And can you please edit the codes below to replace the $SESSION variables if they need to be replaced with cookies.

Below are the php scripts in order to show what is currently happening:

1. **teacherlogin.php** (This is the script where the user enters in their loggin details to log into the application)

<?php

    ini_set('session.gc_maxlifetime',12*60*60);
    ini_set('session.gc_divisor', '1');
    ini_set('session.gc_probability', '1');
    ini_set('session.cookie_lifetime', '0');
    require_once 'init.php'; 
    
     ini_set('display_errors',1); 
     error_reporting(E_ALL);
    
    
    session_start();
    
    ?>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <?php
    
    // connect to the database
    include('connect.php');
    include('member.php');
                            
      /* check connection */
      if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        die();
      }
    
      // required variables (make them explciit no need for foreach loop)
      $teacherusername = (isset($_POST['teacherusername'])) ? $_POST['teacherusername'] : '';
      $teacherpassword = (isset($_POST['teacherpassword'])) ? $_POST['teacherpassword'] : '';
      $loggedIn = false;
      $active = true;
    
      if ((isset($username)) && (isset($userid))){
    	  echo "You are already Logged In: <b>{$_SESSION['teacherforename']} {$_SESSION['teachersurname']}</b> | <a href='./menu.php'>Go to Menu</a> | <a href='./teacherlogout.php'>Logout</a>";
      }
      else{
      
      if (isset($_POST['submit'])) {
    	  
       	  $teacherpassword = md5(md5("g3f".$teacherpassword."rt4"));  
    
        // don't use $mysqli->prepare here
        $query = "SELECT TeacherId, TeacherForename, TeacherSurname, TeacherUsername, TeacherPassword, Active FROM Teacher WHERE TeacherUsername = ? AND TeacherPassword = ? LIMIT 1";
        // prepare query
        $stmt=$mysqli->prepare($query);
        // You only need to call bind_param once
        $stmt->bind_param("ss",$teacherusername,$teacherpassword);
        // execute query
        $stmt->execute(); 
        // get result and assign variables (prefix with db)
        $stmt->bind_result($dbTeacherId, $dbTeacherForename,$dbTeacherSurname,$dbTeacherUsername,$dbTeacherPassword, $dbActive);
    
        while($stmt->fetch()) {
          if ($teacherusername == $dbTeacherUsername && $teacherpassword == $dbTeacherPassword) {
    if ($dbActive == 0) {
        $loggedIn = false;
        $active = false;
        echo "You Must Activate Your Account from Email to Login";
    }else {
        $loggedIn = true;
        $active = true;
          $_SESSION['teacherid'] = $dbTeacherId;
          $_SESSION['teacherusername'] = $dbTeacherUsername;
    }
          }
        }
    
        if ($loggedIn == true){
          $_SESSION['teacherforename'] = $dbTeacherForename;
          $_SESSION['teachersurname'] = $dbTeacherSurname;
          header( 'Location: menu.php' ) ;
          die();
        }
        
        if (!$loggedIn && $active && isset($_POST)) {
        echo "<span style='color: red'>The Username or Password that you Entered is not Valid. Try Entering it Again</span>";
        }
        
           /* close statement */
        $stmt->close();
    
        /* close connection */
        $mysqli->close();
      }
    ?>

Open in new window


**2. member.php** (This script contains `$SESSION` variables to determine which user is logged in. This is a very important script and is included (using `include(member.php) to be able to determine if a user is already logged in or not)

    <?php
    
    if (isset($_SESSION['teacherforename'])) {
    
    $_SESSION['teacherforename'] = $_SESSION['teacherforename'];
    
    }
    
    if (isset($_SESSION['teachersurname'])) {
    
    $_SESSION['teachersurname'] = $_SESSION['teachersurname'];
    
    }
    
    if (isset($_SESSION['teacherid'])) {
    
          $userid = $_SESSION['teacherid'];
          
      }
      
    if (isset($_SESSION['teacherusername'])) {
    	
          $username = $_SESSION['teacherusername'];
          
      }
    		
    		?>

Open in new window

3 **teacherlogout.php** (Finally this is the logout page, when the user clicks on a logout link (which is only displayed in menu.php at moment) then it will go to this page where it displays a message and performs the log out by destroying the session)

    <?php
    
    ini_set('session.gc_maxlifetime',12*60*60);
    ini_set('session.gc_divisor', '1');
    ini_set('session.gc_probability', '1');
    ini_set('session.cookie_lifetime', '0');
    require_once 'init.php'; 
    
    ini_set('display_errors',1); 
    error_reporting(E_ALL);
    
    
    session_start();
    
    ?>
    
    </head>
    
    <?php
    
    include('member.php');
    
    ?>
    
    <body>
    
    <?php
    
    if ((isset($username)) && (isset($userid))){
    session_destroy();
    echo "You have been Logged Out | <a href='./home.php'>Home</a>";
    }
    
    else {
    
    echo "You are Not Logged In";
    
    }
    
    ?>
    
    </body>
    </html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Bruno1990
Bruno1990

ASKER

Thanks for information both of you.

@GaryC123

Can I ask for a basic sample code on what you are asking me to do in order to be able to use Cookies and unique id so that I can implement it into my pages. please
Sorry, I'm leaving right now, if no one else comes along I'll post an example tomorrow.
@GaryC123

Ok cool, thanks
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@Dave Baldwin

At the moment my login system works by extending the session maxlife to 12 hours so the user has 12 hours (or maybe less) to complete their activities on the application, after that they will be timed out.

Now my login system does work, user logins in, they log out, it knows when a user is or is not logged in, it works pretty well.

But I just want to change it so that the user remains logged in until they log out or close the browser, I don't want them to be timed out when session expires.

The reason why I included the php cripts was so that if any of you experts can show how to modify the codes into what it should be in order to get this working, then I can see what needs to be done, and then be able to use the code in order to update other php scripts I currently have.
Are you on shared hosting or are there other PHP web sites on that server?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
All of the responses related to using HTTP cookies are on point and helpful.

https:#a38602179 gives an explanation of the process and provides a link to an Awarded Article with over 50,000 views that discusses these issues in detail, and provides tested-and-working code examples that the Author could copy and use as the basis for his application.