0

I read around that there is a way to keep checking every 30sec or so if the user is still active on the website and if not, logout (or do something else)

I have a basic inactivity logout but it only works if the user is on the website, but if the user closes the browser/tab, it won't work

    if (isset($_SESSION['time'])) {
        $elapsed_time = time() - $_SESSION['time'];
        if ($elapsed_time >= 900) {
            mysql_query("UPDATE `users` SET `status` = '0' WHERE `user_id` = '$session_user_id'");
            session_destroy();
            header('Location:index.php');
        }
    }
    $_SESSION['time'] = time();

how can i do it so that the status changes to 0 only after X amount of inactive time (but it doesn't necessarily have to log the user out - just change the status)?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • Maybe you should have a look at [`ignore_user_abort()`](http://www.php.net/manual/en/function.ignore-user-abort.php) – Shankar Narayana Damodaran Feb 16 '14 at 06:05
  • since the session code would only ever run when a user hits the site (which implies they're still active), you cannot detect when they STOP coming to the site - no hit on the site, no code running. So you'll need external means of detecting idleness - e.g. a script which scans the session files and looks for any which haven't been updated in your timeout period. – Marc B Feb 16 '14 at 06:08
  • @ShankarDamodaran: wouldn't help. session files are locked while in use, which means no other requests for that session could be used. there's session_write_close(), but to update th esession data, you'd have to use session_start again anyways, which would update the session last-accessed time and kill the idle detection code anyways. – Marc B Feb 16 '14 at 06:09
  • Thanks for clarification @MarcB , Yeah I was unsure so I did used the `Maybe` on my comment. Thanks again.! – Shankar Narayana Damodaran Feb 16 '14 at 06:12
  • you could hook one of the session handler functions(garbage collection), and execute code that deletes any sessions that have expired. That way any user visiting the site will trigger a sessions check, otherwise you would have to setup a like cron job that will trigger a script that will do it. – Patrick Evans Feb 16 '14 at 06:12
  • could you give me an example of that code? –  Feb 16 '14 at 06:13
  • Please do not edit your questions to remove the text - they will just be reverted. I don't know why you are blocked, but this is usually resolvable - it is often to do with low-quality questions. If that is the case here, it can be fixed. – halfer Mar 17 '14 at 23:02

2 Answers2

0

hook the session save handler functions, specifically the garbage collection one.

While the below examples show deleting, you could easily modify it to just set an inactivity flag, which can then be read from your inactivity script.

session_set_save_handler docs

PHP <5.4 From: http://www.sitepoint.com/writing-custom-session-handlers/

session_set_save_handler("open", "close", "read", "write", "destroy", "garbage");
function gc($lifetime) {
    $db = new PDO("mysql:host=myhost;dbname=mydb", "myuser", "mypassword");
    $sql = "DELETE FROM session WHERE session_lastaccesstime < DATE_SUB(NOW(), INTERVAL " . $lifetime . " SECOND)";
    $db->query($sql);
}
//below ones are covered in the article.
function open(){}
function close(){}
function read(){}
function write(){}
function destroy(){}

Php 5.4+ From: http://www.php.net/manual/en/class.sessionhandlerinterface.php#example-4769

Note: this example is file based you would just have to modify it to use database

<?php
class MySessionHandler implements SessionHandlerInterface
{
    public function gc($maxlifetime)
    {
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }
    //below functions are covered in the manual
    public function open($savePath, $sessionName){}
    public function close(){}
    public function read($id){}
    public function write($id, $data){}
    public function destroy($id){}
}

$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();

Both rely on a good number of users visiting your site. Otherwise if for instance you dont get users for days the like garbage collection function will not be run for days. In cases like that you would have to setup some other system like a cron job to trigger a script every so often.

Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
  • I think ill have to do it with cronjob as i don't have any users right now.. still at the development of the website part. Could you give me some points of how to achieve this with cronjob? –  Feb 16 '14 at 06:47
0

Delete the files with the following cron:

find .session/ -amin +20  -exec rm {} \;

This will delete session files that have not been accessed for 20 minutes. This will delete all PHP sessions, assuming you are the only person on the server.

More ways to do this are specified in this question: cleanup php session files

Community
  • 1
  • 1
Aziz Saleh
  • 2,687
  • 1
  • 17
  • 27