How can I get the amount of online users on my site (instantly) using only PHP MYSQL and JQUERY? and respectively get the time the user spent on my site
How can I get the amount of online users on my site (instantly) using only PHP MYSQL and JQUERY? and respectively get the time the user spent on my site
One of the ways is to keep the database up to date on the last date the user visited the website and keep it up to date. 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 it indicates that these users are possibly online, after all all the 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>//Repeteacada10segundossetInterval(function(){//Postdecontagem$.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 will send a post to PHP and this request will also get the number of users that are online and will show it in the element of 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 POST, you will see whether or not the session exists. If so, it only updates the last date. If not, it will create a session. Then, in both cases, it will return the number of people online (displaying the number of people that are in the database in the minute! To know the time of permanence just subtract the data_final - start_date .
This is quite limited and not well written, although it is fully functional and there are more criteria that can be added in addition to a mere session cookie.