A
Question: I have verified that it is possible to limit online users on the system via apache(httpd.conf)No, this of limiting sessions in apache is not made for users, the limits in apache would probably be to control connections, which does not guarantee you limit the maximum access of users to a site or page, nor does it have a way to determine from this, since it is possible to maintain a session and there are various types of use for a connection, such as SSE or use the answer HTTP 100 Continue, or else a same user can open more than one connection (for each tab or window that opens).But none of these is the main subject, if you want to limit the number of users, first you need teach your system what a user is, the user could be checked by IP perhaps, what I think No be a good idea, as a same IP on a Network connected in a same Internet provider (ISP) can be used by various computers, so what you can do is use the same sessions, however there is a great PORÉM, it is not possible to detect when a user (which you taught your system "what is/when it is") has left/disconnected.The only way to detect if the user has left is an idle time counter, i.e. if a user is at 5 idle minutes you can "kill" his session and determine for the other users that that session for others is invalid, both factors, as much as "killing" and when disregarding for the others will depend solely on time check, i.e. you will not destroy/kill in truth the session of that user.Maybe someone will tell you about it beforeunload I could help, but I've told you, beforeunload No will work to detect when the user goes out, more details about the subject in: https://pt.stackoverflow.com/a/113155/3635 https://pt.stackoverflow.com/a/80707/3635 Even if you can apply all logic, a database or a database will still be required .txt (which can be much more complicated) to check all users, does not need to be authenticated, the table should be something like:CREATE TABLE usuarios (
id INT NOT NULL UNSIGNED AUTO_INCREMENT PRIMARY KEY,
session VARCHAR(80) NOT NULL,
lastactive TIMESTAMP
)
As users are accessing the table would get soidsessionlastactive122sin5grink0a22l80ej33mcj62018-06-24 01:00:232ul5c6rkacb68suu6rqmd6dubt32018-06-24 01:00:33Each session generated in the table was created at the time the session was entered, i.e. the first time the user accessed, the script would be something like:<?php
session_start();
require 'conexao.php';
define('MAX_USERS', 10); //Limite de 10 usuários
define('TIME_ONLINE', time() - 120);//120 = 2 minutos
$jaEstaOnline = false;
//Verifica se você já esta na "sessão" e dentro do limite de 2 minutos para considerar se estava ocioso ou não
$queryLogado = 'SELECT id TOTAL FROM usuarios WHERE
session = ' . session_id() . ' AND
lastactive > FROM_UNIXTIME(' . TIME_ONLINE . ')';
//Verifica só considera as linhas (usuários) no banco dentro dos minutos
$queryConta = 'SELECT count(*) as TOTAL FROM usuarios
WHERE lastactive > FROM_UNIXTIME(' . TIME_ONLINE . ')';
if ($result = $mysqli->query($queryLogado)) {
$row = $result->fetch_assoc();
$jaEstaOnline = isset($row['id']); //Verifica se existe
$result->free();
}
//Só executa a contagem se você estiver ocioso ou se for o seu primeiro acesso
if (!$jaEstaOnline && ($result = $mysqli->query($queryConta))) {
$row = $result->fetch_assoc();
if (!$row) {
die('Erro na query');
} else if ($row['TOTAL'] > MAX_USERS) {
die('Já tem ' . MAX_USERS . ' usuários acessando');
}
$result->free();
}
//Verifica só considera as linhas (usuários) no banco dentro dos minutos
$query = 'SELECT count(*) as TOTAL FROM usuarios WHERE lastactive < FROM_UNIXTIME(' . TIME_ONLINE . ')';
if ($result = $mysqli->query($query)) {
$row = $result->fetch_assoc();
if (!$row) {
die('Erro na query');
} else if ($row['TOTAL'] > MAX_USERS) {
die('Já tem ' . MAX_USERS . ' usuários acessando');
}
$result->free();
}
//Acaso chegar até aqui então irá atualizar o seu tempo no banco e irá determinar que você não esta ocioso, ou acaso seja o seu primeiro acesso irá te "registrar"
$query = 'REPLACE INTO my_table (session, lastactive) VALUES (session_id(), CURRENT_TIMESTAMP);';
if ($result = $mysqli->query($query)) {
echo 'Você esta conectado';
} else {
die('Você não esta conectado');
}
It would also be interesting to add something to delete all lines over a week for example, so it would decrease unnecessary data in the bankHow to check online users without bankYes it is possible to do with a .txt for example, but it's a lot more complicated, because you're going to have to write a logic on top of it, but something like that would be the next thing you could do:<?php
session_start();
$arquivoDeUsuarios = 'caminho/para/arquivo/usuarios.txt';
define('MAX_USERS', 10); //Limite de 10 usuários
define('TIME_ONLINE', time() - 120);//120 = 2 minutos
$users = array();
if (is_file($arquivoDeUsuarios)) {
$unserialized = unserialize(file_get_contents($arquivoDeUsuarios));
if ($unserialized) {
$users = $unserialized;
}
}
$id = session_id();
//Filtra e só considera os usuários não ociosos
$users = array_filter($users, function ($tempo) {
return $tempo >= TIME_ONLINE;
});
//Verifica se é a seu primeiro acesso, se for vazio é porque é o primeiro ou vocÊ estava ocioso
if (empty($users[$id]) && count($users) > MAX_USERS) {
//Se o count passar do MAX_USERS é por que tem mais de 10 usuários (ou o limite que você definiu)
die('Já tem ' . MAX_USERS . ' usuários acessando');
}
//Atualiza o tempo ou adiciona você acaso for o primeiro acesso
$online[$id] = time();
//Salva os dados
file_put_contents($arquivoDeUsuarios, serialize($users));
But it is important to note that use one .txt can be quite inefficient, someone can be able to record over the information of the other before the expected time, in this case working with LOCK (in php http://php.net/manual/en/function.flock.php ) along with a recursive check would help to avoid problems such as loss of recordings, or record something above, however this would make too slow for users.