Hello Daniweb,

I want to make a custom visitor tracking tool and like Google Analytics it must be able to track how long time visitors spend on each page.

How do you recommend doing this?

I thought of using the Javascript onload event to start counting time serverside and then the onbeforeunload event to do tell the server to end the time count. I'm just skeptic of an infinite visit duration if the visitor's browser for some reason doesn't call the event (ie power outage).

Any ideas? I'm using PHP server side and looking for a most cross browser compatible solution.

I am aware that precise measurement of this is not possible.

Kind regards,

Excizted

Dani AI

Generated

As observed, relying on onbeforeunload alone will give unreliable results (power loss, crashes, backgrounded mobile tabs often never fire it). Combining a short periodic client heartbeat, the Page Visibility API to pause heartbeats when a tab is hidden, a final reliable send on unload, and a server-side timeout gives practical, robust measurements. That also addresses 's concern about phantom sessions and expands on 's heartbeat idea with concrete patterns and fallbacks.

Suggested client pattern (minimal, production code should handle errors and ID injection from the server):

// client heartbeat (simplified)
const SID = window.SERVER_SID || getCookie('sid');
const INTERVAL = 15000; // ms
function beat(final=false){
  const body = JSON.stringify({sid: SID, path: location.pathname, ts: Date.now(), final});
  if (navigator.sendBeacon) {
    navigator.sendBeacon('/track.php', body);
  } else {
    fetch('/track.php', {method:'POST', body, keepalive:true, headers:{'Content-Type':'application/json'}});
  }
}
let timer = setInterval(beat, INTERVAL);
document.addEventListener('visibilitychange', ()=> {
  if (document.hidden) { clearInterval(timer); beat(); } else { beat(); timer = setInterval(beat, INTERVAL); }
});
window.addEventListener('pagehide', ()=> beat(true), {passive:true});

Server logic (concept):

// track.php (concept)
$payload = json_decode(file_get_contents('php://input'), true);
$sid = $payload['sid'] ?? session_id();
$ts = $payload['ts'] ?? time()*1000;
$final = !empty($payload['final']);
// upsert visit: if no row insert first_ts=last_ts=$ts
// else delta = $ts - last_ts; if delta <= TIMEOUT add to accumulated_ms; update last_ts
// if $final or now-last_ts > TIMEOUT consider session closed

Tuning notes: heartbeat 10–30s, server timeout = 2x–4x interval (or fixed 60s), aggregate updates (Redis + flush) to avoid heavy DB writes, handle SPA route changes as navigation. Use Page Visibility API and Navigator.sendBeacon for best reliability. For reference on how analytics systems treat session duration, see Google Analytics session timing notes ().

Recommended Answers

All 2 Replies

You could use any server side techonology to do that if you want to implement it from scratch by yourself. One problem that you need to solve is that how would you know that a visitor is still spending time on a page of your website. For example, a user opens your web page and left to do something else. Another case is when a user opens your web page and close the browser. I am guessing that one way to do it is to compute from the first request is made until the time out... Not sure...

Try something in ajax/javascript/jquery/php or your choice and have the page ping the server every 'whatever you decide is reasonable' seconds with the SESION_ID you created in php. I would setup every page so they all ping a specific page with the SESSION_ID.

Register each SESSION_ID with the page. I would make a new timer from my timer class that is reset if the ping comes back and fires off the time spent to wherever I needed it.

I know its all theory and easy to say.

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.