I'm making a couple of assumptions here.
I'm assuming, for whatever reason, you want to be able to track the expired session cold, that is, no supplementary tracking of session data via a database or a second 'hidden' session that acts as a structure to determine when a pseudo-session has expired and acting appropriately.
I'm also assuming that hack attempts on your session aren't important at this point. Man-in-the-middle and XSS attacks can capture session ID's and plug them into your system and it would be hard to detect.
This sort of thing is handled by session cookies in php by default. I'm also assuming that your session identification and session start are also handled by cookies.
There's almost no way of doing this 'live', which is to say, keep a socket open to the server to detect the moment the session expires. PHP was not designed to work that way; the security issues are expansive. As well, if you're allowing someone to access your server remotely through a secure channel, why are you bothering with sessions in the first place?
$sessionCookie = 'myPHPSessCookieName';
$isSessionExpired = false;
if (isset($_COOKIE[$sessionCookie])) {
// check cookie expiry time to show warnings / near expiry behaviours
} else {
// handle missing cookie / session
$isSessionExpired = true;
}
define('SESSION_EXPIRED', $isSessionExpired);
session_start(['name' => $sessionCookie]);
Checking for the cookie has to happen prior to starting the session otherwise you run the risk of giving yourself a false positive.
[edit: javascript solution]
If you wish to produce a behaviour that simulates a socket, javascript can do this. The client's browser will ping the server with AJAX requests to check the status of their session, and once it detects that it is expired, you can induce a behaviour of your choice. Note: javascript in its current state is fundamentally insecure. All of the data and security related work ought to be done by the server if at all possible.
client.php:
<script>
$(function(){
var messageElem = $('#selectorForDisplayElementHere');
var timeoutID = null;
var checkSession = function(){
$
.ajax({/* your ajax params: url, data, dataType, method etc. */})
.then(function(response){
messageElem.html(response.html);
if (response.stop === 1) {
clearTimeout(timeoutID);
}
});
};
var timeoutID = setInterval(checkSession, 5000); // Every 5 seconds
});
</script>
ajax.php:
$response = ['html' => '', 'stop' => 0];
if (SESSION_EXPIRED) {
$response ['html'] = '<b>Your session has expired. Please log in again.</b>';
$response['stop'] = 1;
}
echo(json_encode($response));
This is a very simple handling system that can be readily enhanced with all sorts of functionality. It uses the ubiquitous jQuery library and standard php and html/javascript functionality.