visitor counter in php when open/close or leave the page

1.7k views Asked by At

Possible Duplicate:
how can I make visitor counter in php?

I want to insert when page open/close or leave but not onunload .. the below code help me to insert when open the page , but not when close or leave

session_start();
if (!isset($_SESSION["visits"]))
    $_SESSION["visits"] = 0;
if ($_SESSION["visits"] > 1){
    echo 'visit='.$_SESSION["visits"];
    echo "You hit the refresh button!";}
else{
    mysql_query(
        "INSERT INTO najd_visit( visit_userId, visit_staticId, visit_page,
            visit_enterTime)VALUES ('$userId', '$Sid', '$title', '$date') ");
    $_SESSION["visits"] = $_SESSION["visits"] + 1;
    echo 'visit='.$_SESSION["visits"];
    echo "This is my site";
}
2

There are 2 answers

1
Laurence On

You cant run something via PHP when someone "leaves" the page - because the browser nevers sends anything to your server to trigger the script.

You only possible option is to use javascript and run it as they leave - but its going to be temperamental and unreliable at best.

2
Yehonatan On

You can use Javascript and Ajax. Javascript: Intercept page exit event Ajax - http://www.w3schools.com/ajax/default.asp

Edit: I don't think that you can do it without unload, php is a server-side language, not user-side.