i am new to php. i want to know how to logout a user when he/she is idle for sometime.

Thanks in advance

Dani AI

Generated

Short answer: combine a small client-side idle watcher (so the browser can act while a page is open) with a server-side session timeout (so the server always enforces logout on the next request). This brings together the practical points already raised by , and while avoiding reliance on a single mechanism.

Why both? Client code can detect “real‑time” inactivity and proactively POST to a logout endpoint. Server code is the ultimate authority — every protected page should still check a session timestamp and expire the session if it’s stale. Put the server check in a single include or your front controller / base controller so every request runs it.

Example client-side watcher (place in your common JS bundle or header):

(function(){
  var IDLE_MS = 5 * 60 * 1000; // adjust
  var timer, KEY = 'dw_lastActivity';

  function reset(localUpdate){
    clearTimeout(timer);
    if (localUpdate !== false) try { localStorage.setItem(KEY, Date.now()); } catch(e){}
    timer = setTimeout(onIdle, IDLE_MS);
  }

  function onIdle(){
    if (navigator.sendBeacon) {
      navigator.sendBeacon('/logout.php');
      location = '/login.php';
    } else {
      fetch('/logout.php',{method:'POST',credentials:'same-origin'}).finally(function(){ location = '/login.php'; });
    }
  }

  ['mousemove','keydown','mousedown','touchstart','scroll'].forEach(function(e){ window.addEventListener(e, function(){ reset(); }, true); });
  window.addEventListener('storage', function(ev){ if (ev.key === KEY) reset(false); });
  reset();
})();

Server-side: a small snippet you include at top of protected pages (or in middleware):

<?php
session_start();
$timeout = 300;
if (isset($_SESSION['last_active']) && time() - $_SESSION['last_active'] > $timeout) {
  session_unset(); session_destroy();
  header('Location: /login.php'); exit;
}
$_SESSION['last_active'] = time();
?>

Notes and gotchas:

  • Destroying the server session logs out all tabs for that browser (cookies are shared). If you want a single-tab UI timeout, don’t destroy the session — just show a local “expired” UI.
  • Always rely on the server check as a fallback (JS can be disabled).
  • For long forms, offer a warning modal and a “stay logged in” action that resets the timer.
  • Use HTTPS, HttpOnly cookies, and regenerate session IDs to reduce session‑fixation risks.

This pattern answers the “where to place code” question: client code in a shared header/script, server checks in a single include/front controller so it applies app-wide.

Recommended Answers

All 8 Replies

If you mean idle as in sat on a webpage for too long and you want to force a logout then PHP can't help as it's server side. JavaScript would work on timers.

Otherwise PHP using timers can only log out a user when they send another request after this time period is up.

If you are asking for a "real-time" logout action after some time i guess you'd have to use some Ajax/Javascript.
But i would use

<meta http-equiv="Refresh" content="300; url=">

This will redirect the page after 300 seconds(5 min).
Obviously the meta code will restart its timer when a user clicks a link, or any action that would update the code..

If you are asking for a "real-time" logout action after some time i guess you'd have to use some Ajax/Javascript.
But i would use

<meta http-equiv="Refresh" content="300; url=">

This will redirect the page after 300 seconds(5 min).
Obviously the meta code will restart its timer when a user clicks a link, or any action that would update the code..

That's actually a nice simple way, using JavaScript might be overdoing it then in this case ...

You have to put a token in your security checks that is renewable for each page click. That is a session variable storing last time user accessed a page and when user sends new request find difference btwn current time and session variable. If it is greater than permissible time kill session and send him to login page
This thread have snippet that illustrates what I say

EDIT
I found a good question with nice answers on SO

yes, how to do this? i need some example coding for user who is idle for some time. and also where to place the coding?

If you mean idle as in sat on a webpage for too long and you want to force a logout then PHP can't help as it's server side. JavaScript would work on timers. Otherwise PHP using timers can only log out a user when they send another request after this time period is up.

Thanks evstevemd.

I saw that two url's. In my application i have many pages, in that one of the page i pasted that code. eg: hr->employee->view i pasted the code. i visit the hr->emplpoyee->view page and i moved some page in the same application. after some time which is i mentioned as logout time in code. i revisit hr->view->employee. its getting logout. but i need to logout only the user who is idle for some time in a page.


You have to put a token in your security checks that is renewable for each page click. That is a session variable storing last time user accessed a page and when user sends new request find difference btwn current time and session variable. If it is greater than permissible time kill session and send him to login page
This thread have snippet that illustrates what I say

EDIT
I found a good question with nice answers on SO

What Sorcher said will do the job ... looks like your navigation tree relates to company employees .. is this for your job?

Have a look at : http://www.w3schools.com/js/js_timing.asp

If you are asking for a "real-time" logout action after some time i guess you'd have to use some Ajax/Javascript.
But i would use

<meta http-equiv="Refresh" content="300; url=">

This will redirect the page after 300 seconds(5 min).
Obviously the meta code will restart its timer when a user clicks a link, or any action that would update the code..

There's too much of undecided spec, for instance if a user has timed out, what do we do .. keep the page visible, in that case Ajax would be useful or redirect them to another page in which case the above quote would work, what about if JavaScript is disabled when using JavaScript ...

Things need deciding first ...

Thanks evstevemd.

I saw that two url's. In my application i have many pages, in that one of the page i pasted that code. eg: hr->employee->view i pasted the code. i visit the hr->emplpoyee->view page and i moved some page in the same application. after some time which is i mentioned as logout time in code. i revisit hr->view->employee. its getting logout. but i need to logout only the user who is idle for some time in a page.

The code still applies. You just put that code in a file and may be a function or whatever way you want to organize. Then you include the file at the top of any page.
If you use MVC approach then work becomes easy, you put that code either in your front controller or in your routing class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.