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.