0

I am trying to create a system where, when the user is inactive for x amount of time, they should are logged out and sent back to 'index.php'. I am using the code I found here - http://cookbooks.adobe.com/post_Set_a_time_limit_on_a_login_session__PHP_-16701.html and I put it in a function like this:

phpfunc/inactivity.php

<?php

function inactivity() {
    // create a session 
    if (!isset($_SESSION)) {
        session_start();
    }

    // store the current time
    $now = time();

    // get the time the session should have expired
    $limit = $now - 60*20;

    // check the time of the last activity
    if (isset ($_SESSION['last_activity']) && $_SESSION['last_activity'] < $limit) {
        // if too old, clear the session array and redirect
        $_SESSION = array();
        header('../index.php');
        exit;
    } 
    else {
        // otherwise, set the value to the current time
        $_SESSION['last_activity'] = $now;
    }
}

?>

Then, I call the function like this...at the top of my protected page

templates/login_success.php:

<?php
require('/Users/Eamon/Sites/phpfunc/inactivity.php');
inactivity();

if($_SESSION['username'] === null){
    header("location: ../index.php");
}
?>

<h1>Login Successful</h1>
<h2>Username: <? echo $_SESSION['username']?></h2>
<div id="logoutlinkdiv" >
    <a href = "#" >Log out</a>
</div>

I can login - and all the inactivity stuff seems to work. I tested it by adding a few echo statements here and there...and after login I tried going to the protected page - like this "localhost/~Eamon/templates/login_success.php" and it lets me see it...after 20 minutes I have to sign in again. However, I have a page that loads once the user logs out (after clicking the "logoutlinkdiv" link) - and it has a link on it to log in again. When I click this link, I get the message "Wrong Username or Password" - which can be found in the below file (which gets executed upon login). After 20 more minutes, I can login again without getting this error.

checklogin.php

<?php

session_start();

$host="localhost"; // Host name
$username="root"; // Mysql username
$password="bonjour3"; // Mysql password
$db_name="itit"; // Database name
$tbl_name="members"; // Table name

// Connect to server and select databse.
$mysqli = new mysqli("$host", "$username", "$password", "$db_name")or die("cannot connect");

// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

$sql = $mysqli->prepare("SELECT * FROM $tbl_name WHERE username=? and password=?");
$sql->bind_param('ss',$myusername,$mypassword);
$sql->execute();
$sql->store_result();//apply to prepare statement
$numRows = $sql->num_rows;

if($numRows === 1){
    $_SESSION['username'] = $myusername;
}
else {
    echo "Wrong Username or Password";
    session_destroy();
}
?>

Here is the aforementioned logout page (where the user can login again...the trouble page!):

templates/logout.php

<?php
session_start();
session_destroy();
?>

<div id="loginlinkdiv" >
    <h2>You have been logged out.</h2>
    <a href = "#">Log in</a>
</div>

In case it is relevant...here is the jquery I am using. I am making an SPA - so jquery is loading and emptying things for me in the "main" div on index.php - here:

index.php

<?php session_start(); ?>

<!DOCTYPE html>
<html>
<head>
<title>it IT</title>
    <script src="reqscripts/jquery.js" type="text/javascript"></script>
    <script src="js/application.js" type="text/javascript"></script>
</head>
<body>
    <div id="main"></div>
</body>
</html>

UPDATE

Following the suggestion - I tried the first answer on this page:

How do I expire a PHP session after 30 minutes?

I changed two files.

phpfunc/inactivity.php now looks like this:

<?php

function inactivity() {

    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
        header("/Users/Eamon/Sites/index.php");
    }

    $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
}

?>

and templates/login_success.php looks like this:

<?php
require('/Users/Eamon/Sites/phpfunc/inactivity.php');
session_start();
inactivity();
?>

<h1>Login Successful</h1>
<h2>Username: <? echo $_SESSION['username']?></h2>
<div id="logoutlinkdiv" >
    <a href = "#" >Log out</a>
</div>

Still the same problem appears to be happening...and I think I caught a new glitch. When I click the login link (templates/logout.php) it brings me to index.php. I try to login, but the information in the textboxes gets reset, and seemingly nothin happens. When I try again - I get "Wrong Username or Password" again. Also - <? echo $_SESSION['username']?> is not showing up on the login_success.php page anymore.

UPDATE

It seems as if I'm not getting signed in because <? echo $_SESSION['username']?> still doesnt output anything.

Community
  • 1
  • 1
ewizard
  • 2,801
  • 4
  • 52
  • 110
  • Why cant you just set it in php.ini or htaccess: http://www.php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime (`session.gc-maxlifetime` directive)? A whole lot easier! – jtheman Jun 18 '13 at 14:00
  • Possible duplicate of http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes – Filippos Karapetis Jun 18 '13 at 14:01
  • @jtheman thanks for pointing me in the right direction - just what i needed. – ewizard Jun 18 '13 at 14:03
  • @jtheman Filippo's link says that `session.gc-maxlifetime` isn't good...is this true? – ewizard Jun 18 '13 at 14:23
  • Well I don't disagree with that, the answer is initiated. Possibly more rock-solid controlling the timeout manually than relying on the server. My experience however is that using the simple ini directive it is working 100%. – jtheman Jun 18 '13 at 14:30
  • @jtheman what is ini directive? do i only need to use `session.gc-maxlifetime` what do i set in php.ini or htaccess? – ewizard Jun 18 '13 at 14:31
  • @jtheman do i just need this? `session.gc_maxlifetime` in php.ini or something? – ewizard Jun 18 '13 at 14:35
  • On many shared servers you don't have access to php.ini, but you can set the directive in a .htaccess file. Add `php_value session.gc.maxlifetime 1800` (60sx30m=1800s) to your .htaccess file if you have it or create an empty text file with that name and add the line. – jtheman Jun 18 '13 at 14:36

1 Answers1

0

Option one:

use session.gc_maxlifetime

ini_set('session.cookie_lifetime',  600);
session_start();

http://php.net/manual/en/function.session-set-cookie-params.php

This value (default 1440 seconds) defines how long an unused PHP session will be kept alive. For example: A user logs in, browses through your application or web site, for hours, for days. No problem. As long as the time between his clicks never exceed 1440 seconds. It's a timeout value.

option two:

session.cookie_lifetime

This value (default 0, which means until the browser's next restart) defines how long (in seconds) a session cookie will live. Sounds similar to session.gc_maxlifetime, but it's a completely different approach. This value indirectly defines the "absolute" maximum lifetime of a session, whether the user is active or not. If this value is set to 60, every session ends after an hour a minute.

Option Three:

session_start();
// set time-out period (in seconds)
$inactive = 600;

// check to see if $_SESSION["timeout"] is set
if (isset($_SESSION["timeout"])) {
    // calculate the session's "time to live"
    $sessionTTL = time() - $_SESSION["timeout"];

    if ($sessionTTL > $inactive) {
        session_destroy();
        header("Location: /logout.php");
    }
}

$_SESSION["timeout"] = time();
Haver
  • 443
  • 2
  • 11
  • Have you read this: http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes – jtheman Jun 18 '13 at 14:41
  • @user1752647 I think u mean this `ini_set('session.gc-maxlifetime', 60*30);` not this `ini_set('session.cookie_lifetime', 600);` – ewizard Jun 18 '13 at 14:52
  • @jtheman where do i put `ini_set('session.gc-maxlifetime', 60*30);`? – ewizard Jun 18 '13 at 14:52
  • @jtheman I have this in my php.ini file `session.gc_maxlifetime = 1440` so are you saying i dont have to worry about anything? or do i need a line of code somewhere? – ewizard Jun 18 '13 at 14:58
  • @jtheman can i go back to using just `session_start()` basically is what im asking – ewizard Jun 18 '13 at 15:01
  • so something like `if(!isset($_SESSION)) { session_start } else { ...` ? – ewizard Jun 18 '13 at 15:07
  • @jtheman I cleaned up my progress with a new question here: http://stackoverflow.com/questions/17172816/session-gc-maxlifetime-php-ini-wrong-login-process – ewizard Jun 18 '13 at 15:25