online users and time spent on the site

Asked

Viewed 2,054 times

3

How can I get the amount of users online on my site (instantly), using only PHP MYSQL and JQUERY? and respectively get the time the user spent on my site

  • 1

    Have you ever used Google Analytics? It does this.

  • Would not like to use external services

1 answer

6

One of the ways is to keep updated in the database the record of the last date that the user accessed the website and keep updated. In this example I will update the registration every 10 seconds. So if the last user access is recent, at least in the last 60 seconds indicates that these users are possibly online, after all data is updated every 10 seconds.

1. Database:

CREATE TABLE visitas 
  ( 
     id          INT(11) UNSIGNED auto_increment PRIMARY KEY, 
     data_inicio DATETIME NOT NULL, 
     data_final  DATETIME NOT NULL 
  ) 

2. Client-Side:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script>

// Repete a cada 10 segundos
setInterval(function () {
   // Post de contagem
    $.post("visitas.php", {contar: '',}, function(data) {
        // Exibe o número de online
        $('#Online').text(data); 
    });
}, 10000);

</script>

<span id='Online'>0</span>

Every 10 seconds you will send a post to PHP and this request will also get the amount of users who are online and will show it in the id equal to Online.

3. Server-Side:

if (isset($_POST['contar'])) {

    // Inicia sessão ou resume sessão existente:
    session_start();

    $data['atual'] = date('Y-m-d H:i:s');
    $data['online'] = date($data['atual'], strtotime("-1 minutes"));

    // Se o usuário já estiver online, existindo sessão:
    if (isset($_SESSION['visitante'])) {

        mysqli_query($con, "UPDATE Visitas SET data_final = '" . $data['atual'] . "' WHERE id = '" . $_SESSION['visitante'] . "'");

    }else{

        $insert = mysqli_query($con, "INSERT INTO Visitas VALUES (0, '" . $data['atual'] . "', '" . $data['atual'] . "')");

        $_SESSION['visitante'] = mysqli_stmt_insert_id($insert);

    }

    session_write_close();

    // Para retornar os últimos usuários online:    
    $select = mysqli_query($con, "SELECT count(id) as Online FROM Visitas WHERE data_final >= '" . $data['online'] . "'");

    list($online) = mysqli_fetch_row($select);

    echo $online;

}

Whenever you receive the POST you will see whether or not the session exists. If there is, it only updates the last date. If not, it will create a session. Then, in both cases, it will return the number of people onlines (displaying the number of people who are in the database in the minute! To know the length of stay just subtract the final date - starting date.

This is quite limited and not well written, although it is fully functional there are more criteria that can be added besides a mere session cookie.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.