alebash
alebash

Reputation: 195

How to check if user has left certain page

Right now, when the user comes to a page a session is started; that's working fine. But how can I detect when a user leaves that page? I need it so that when the user leaves the page, the session is destroyed.

Upvotes: 3

Views: 2504

Answers (5)

fyr
fyr

Reputation: 20859

HTTP is an asynchronous protocol. Asynchronous connections with user sessions are valid in a certain period of time. This time is also refered as expiry time. Therefore sessions have an expiry time. And this time will be renewed while a user accesses your page and invalidated(destroyed) if he does no action in this timeframe.

There is no other way to determine if a user leaves your page.

Upvotes: 1

Dereleased
Dereleased

Reputation: 10087

That's not really how the internet works; you could try sending a signal with onbeforeunload() but it's not a guarantee. Since session garbage is just a probability, and I don't know what your viewership looks like, I'd suggest putting something like this in a common file:

if (isset($_SESSION['last_seen']) && $_SESSION['last_seen'] < time() - 3600) {
    session_unset();
    session_destroy();
    header('Location: logout_or_whatever.php');
    exit;
}
$_SESSION['last_seen'] = time();

Upvotes: 0

Rodaine
Rodaine

Reputation: 1024

You wouldn't be able to use PHP to detect the user leaving the page, but you can send an ajax request via javascript on the unload event to destroy that users session.

Related post: Can you fire an event in JavaScript before the user closes the window?

Upvotes: 3

wanovak
wanovak

Reputation: 6127

If you're only worried about pages within your website:

if($_SERVER['REQUEST_URI'] !== 'page_with_session.php'){
    session_destroy(); // Kill session for all pages but page_with_session.php
}

Upvotes: 2

RiaD
RiaD

Reputation: 47620

It is impossible in general case

Upvotes: 0

Related Questions