how can I make visitor counter in php?

3.4k views Asked by At

How I can count visitors ?? I want to insert when open the page and when close or leave the page but not onunload And I don't want to insert when refresh the page the below code help me to insert when open the page , but not help when close

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
Mateusz Rogulski On

Try add session_start() to handle your session request.

http://php.net/manual/en/function.session-start.php

0
Whisperity On

To use $_SESSION, you need to call session_start() somewhere beforehand.

I think the code should look like this:

session_start();
if ( !isset($_SESSION['visited']) )
{
    echo "This is your first visit.";
    $_SESSION['visited'] = TRUE;

    // Do the MySQL query here
} else {
    echo "You hit the refresh button.";
}

echo "This is my site.";

This way, when a new user first visits your site (with a new session), his/her visit will be stored in the database and we will have a variable in the session set, so after a refresh button, the information about the visit won't be added to the database again.