2

When a user logs in to a website successfully, that event creates a session named 'loggedin' and sets it to true.

if (criteria satisfied){
    $_SESSION['loggedin'] = true;}
else { ... }

How can this session be made to expire upon the user exiting the website?

Exiting the website means directly leaving the website. Whether that be closing the tab, browser or visiting another website, it means any instance where the user leaves the website.

I have checked other questions before asking this question but none seem to answer this directly, all seem to deal with unique instances relevant to each asker.

RSM
  • 14,540
  • 34
  • 97
  • 144
  • 4
    What does "exiting the website" mean to you? – jprofitt Mar 19 '12 at 12:32
  • 1
    There are numerous questions about this. Please review them: http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes – sikander Mar 19 '12 at 12:34
  • @ryan you mean to track closing of tabs/windows? – hjpotter92 Mar 19 '12 at 12:35
  • Check updated question. @sikander I have checked them before I posted this, but none, that I can see actually answer this exact question directly. Most are after time limits – RSM Mar 19 '12 at 12:37
  • possible duplicate of [PHP run a script when a session expires](http://stackoverflow.com/questions/8416159/php-run-a-script-when-a-session-expires) - when the session expires. If you need more help, you need to tell what "exiting the website" means. The diverse variants have been asked already (multiple times). – hakre Mar 19 '12 at 12:38

2 Answers2

3

try putting:

session.cookie_lifetime = 0; 

in php.ini. This will remove the session cookie if the user is exiting your website (by closing the browser, for example if she shuts the computer down). See session.cookie_lifetime.

hakre
  • 193,403
  • 52
  • 435
  • 836
ZiTAL
  • 3,466
  • 8
  • 35
  • 50
  • 1
    +1, Note: Will not work for closing tabs or visiting another website. Additional note: can never work for closing tabs and visiting other websites because the user can have multiple tabs of your site open and the server will never know how many tabs the user has. (so it can not delete the session when the last tab is closed) – Kaii Mar 19 '12 at 12:50
0

A session on the client side is just a cookie with the session's ID # in it.

You can set your cookie's expiration to be very small but if someone is idle on a page there session might expire. You can put a hidden IFRAME on all your pages (master page / master template) with an META refresh that will refresh the session cookie expiration.

You could also attempt to use the onUnload JavaScript event to make an Ajax call to your LogOut page which could abandon the session and clear the cookie.

Louis Ricci
  • 20,804
  • 5
  • 48
  • 62