Skip to content Skip to sidebar Skip to footer

How Unset Session When Close The Web Page In Php

How can I unset the SESSION when I close the page by clicking [x] (not onunload). I want to insert when opening the page and when closing, but I don't want to insert when refreshin

Solution 1:

Make ajax calls to your php on JS events of page load and right before leave (onbeforeunload event).

Better rely on a JS library like jQuery, as direct JS cross-browser implementation of both event listeners is quite tricky to code.

Upd. Thanks to @piers comment I see my solution is not complete as it would count up on page refresh. If I understand the task correctly, the goal is to count page opens and leaves, not counting refresh events.

So, perhaps, there's no real need to unset the session on page close - let it vanish itself on timeout at server?

You can use session_id to determine if the page/session pair is unique. For instance, you can keep visited page URLs in session, to check if you already counted that in:

<?php$uri = $_SERVER['REQUEST_URI'];
if( is_set( $_SESSION['seen']) {
    if( !in_array( $uri, $_SESSION['seen'])){
        countup( $uri);
    } else {
        // already counted that page
    }
} else { // session doesn't have the seen array yet
    countup( $uri);
}

functioncountup($uri) {
    $_SESSION['seen'][] = $uri;
    mysql_query( "
        INSERT INTO najd_visit 
        ( visit_userId, visit_staticId, visit_page, visit_enterTime)
        VALUES ('$userId', '$Sid', '$title', '$date')
    ");
    echo"This is my site";
}
?>

Solution 2:

session_set_cookie_params(0);
session_start()

Manual: http://www.php.net/manual/en/function.session-set-cookie-params.php


To clarify:

You want to kill a session when a user no-longer visits your site? But if they stay on your site (back button, forward etc) then you want to keep the session.

To answer the direct question - you can't track when a user closes the browser - i.e. when they click on the "x", as requested in the comments.

You can't use "onunload" because it happens when a user may be flicking to a page stil on your site.

So you have four options:

1) Manually control your sessions using cookies, and set the cookies to expire when the browser session ends.

2) Mofify session_set_cookie_params(0) http://www.php.net/manual/en/function.session-set-cookie-params.php so the session ends when the browser closes.

3) Modity php.ini session.cookie_lifetime to 0 (sessions end when the browser closes - same as above but more global)

4) Have an ajax call back every 30 seconds, and if you don't get a callback after a minute, assume the browser's been closed and then kill the sessions. (Requires quite a lot of handling!)

Post a Comment for "How Unset Session When Close The Web Page In Php"