Jump to content

automatic logout code not working


webguync

Recommended Posts

Hello,

 

I have some code that in theory should be logging out automatically after 60 minutes. It doesn't appear to be working though, and I am not sure how to debug. Any ideas? Also, how would I echo a message prior to logout?

 

session_start();
/*logout after 60 minutes*/
function login_validate() {
/*Set the timeout on a login session. */

$timeout = 60*60;
$_SESSION["expires_by"] = time() + $timeout;
}

 

 

Link to comment
Share on other sites

Well, it looks like you're storing the timeout "time" in a session. You would have to have that page call back to the server every so often to check if the time has expired, if it has then you could print a message out to the page, but again, you have to communicate back to check the session. If that makes sense.

Link to comment
Share on other sites

I found some code in one of my PHP books, for an automatic logout, but when I add it, I can no longer login at all. Just get redirected back to the login page.

 

Here is the code I am trying:

 

/ini_set("display_errors","1");
//ERROR_REPORTING(E_ALL);

session_start();
ob_start();
//set a time limit in seconds
$timelimit=15;
//get the current time
$now = time();
//where to redirect if rejected

if(isset($_POST['submit'])) {
   if(empty($_POST['username']) || empty($_POST['pwid']) ) {
    echo "<h2 style='color:#039;font-size:14px;font-family:arial, helvetica,sans-serif'>Please fill in both your username and password to access the editor exam. You will be redirected back to the login screen in 5 seconds</h2>";
  echo "<meta http-equiv='refresh' content='5; url=EditorLogin.php'>";
                exit;
   }
//if time limit has expired, destroy session and redirect
elseif ($now > $_SESSION['start'] + $timelimit) {
//empty the $_SESSION array
$_SESSION = array();
// invalidate the session cookie
if (isset($_cookie[session_name()])) {
setcookie(session_name(), '', time()-86400, '/');
}
//end session and destroy with query string
session_destroy();
header("Location: {$redirect}?expired=yes");
exit;
}
//if it's got this far, it's ok to update start time
else {
$_SESSION['start'] = time();
}




$con = mysql_connect("localhost","ETSI","Editor") or die('Could not connect: ' . mysql_error());

mysql_select_db("ETSI_Internal") or die(mysql_error());






   // Create the variables again.
   
   $username = mysql_real_escape_string($_POST['username']);
   $pwid = $_POST['pwid'];
//set a time limit in seconds
$timelimit=15;
//get the current time
$now = time();
//where to redirect if rejected
   // Encrypt the password again with the md5 hash. 
   // This way the password is now the same as the password inside the database.
   //$pwid = md5($pwid);

   // Store the SQL query inside a variable. 
   // ONLY the username you have filled in is retrieved from the database.
   $query = "SELECT username,pwid,name
           FROM   TableName
           WHERE
           pwid = '$pwid'
           AND
           username='$username'";

   $result = mysql_query($query) or die(mysql_error());
   if(mysql_num_rows($result) == 0) { 
      // Gives an error if the username/pw given does not exist.
      // or if something else is wrong.
     echo "<h2 style='color:#039;font-size:14px;font-family:arial, helvetica,sans-serif'>You have entered a username or password that does not match our database records. please try again. You will be directed back to the login screen in 5 seconds. </h2> " . mysql_error();
echo "<meta http-equiv='refresh' content='5; url=EditorLogin.php'>";
exit();
/*
this would benefit from a redirect to a page giving better information to
the user and maybe logging some errors.
*/
   } else {
      // Now create an object from the data you've retrieved.
      $row = mysql_fetch_object($result);
      // You've now created an object containing the data.
      // You can call data by using -> after $row.
      // For example now the password is checked if they're equal.

      // By storing data inside the $_SESSION superglobal,
      // you stay logged in until you close your browser.
  $_SESSION['name'] = $row->name;
     $_SESSION['username'] = $username;
      $_SESSION['sid'] = session_id(); 
      // Make it more secure by storing the user's IP address.
      $_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
      // Now give the success message.
      // $_SESSION['username'] should print out your username.

//move this to after your redirect further below..
      
   }
}

// Start a session. If not logged in will be redirected back to login screen.

if(!isset($_SESSION['username'])){
header("Location:EditorLogin.php");
exit;
}
echo "<div id='welcome'><h3>Welcome! You are now logged in " . $_SESSION['name'] . "</h3>";

echo "<a class='logout' href='logout.php'>Logout</a></div>";

?>

Link to comment
Share on other sites

  • 1 month later...

Every time the page is loaded, check to see time current time() and compare it to what's stored in $_SESSION["expires_by"].

 

What's this for bullshit? Are we now storing a session expiration date on an expiring session? Just use:

 

ini_set('session.save_path', SESSION_SAVE_PATH);

ini_set('session.gc_probability', 100);// not recommended but will make sure the session is removed immediatly after expiration

session_set_cookie_params(3600);//cookie expires 3600 seconds after initialization

session_start();

 

Another method is using a database as it allows for more control as:

 

SELECT * FROM sessions WHERE id = $id AND last_modified + lifetime > now()

 

This will effectively expire the session when last_modified + lifetime <= now() altough the deletion of the record may well be a few minutes later. It has also other advantages like a session will be re-used instead of creating a new one whenever the user logs-in before the session expires by which the last_modified time is modified and the expiration is delayed

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.