Ответ 1
http://coursesweb.net/php-mysql/register-show-online-users-visitors_t
Вот хороший учебник, это то, что вам нужно.
Зарегистрировать и показать онлайн-пользователей и посетителей
Счет пользователей и посетителей онлайн с использованием таблицы MySQL В этом уроке вы можете узнать, как регистрировать, подсчитывать и отображать на своей веб-странице количество пользователей и посетителей онлайн. Принцип таков: каждый пользователь/посетитель зарегистрирован в текстовом файле или базе данных. Каждый раз, когда открывается страница веб-сайта, php script удаляет все записи старше определенного времени (например, 2 минуты), добавляет текущего пользователя/посетителя и берет количество оставшихся записей.
Вы можете хранить онлайн-пользователей и посетителей в файле на сервере или в таблице MySQL. В этом случае я считаю, что использование текстового файла для добавления и чтения записей выполняется быстрее, чем их хранение в таблице MySQL, что требует больше запросов.
Сначала он представил метод записи в текстовом файле на сервере, чем метод с таблицей MySQL.
Чтобы загрузить файлы со сценариями, представленными в этом учебном курсе, щелкните → Подсчитать онлайн-пользователей и посетителей.
• Оба сценария могут быть включены в ".php" файлы (с include()) или в ".html" файлы (с), как вы можете видеть в примерах, представленных в нижней части этой страницы; но сервер должен запускать PHP. Сохранение онлайн-пользователей и посетителей в текстовом файле
Чтобы добавить записи в файл на сервере с PHP, вы должны установить разрешения CHMOD 0766 (или CHMOD 0777) для этого файла, чтобы PHP мог записывать в него данные.
1. Создайте текстовый файл на вашем сервере (например, с именем "userson.txt" ) и дайте ему разрешения CHMOD 0777 (в вашем приложении FTP щелкните правой кнопкой мыши на этом файле, выберите "Свойства", затем выберите "Чтение", "Запись", и "Выполнить" ). 2-Создайте файл PHP (с именем "usersontxt.php" ) с кодом ниже, затем скопируйте этот файл php в тот же каталог, что и "userson.txt". Код для usersontxt.php
<?php
// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start(); // start Session, if not already started
$filetxt = 'userson.txt'; // the file in which the online users /visitors are stored
$timeon = 120; // number of secconds to keep a user online
$sep = '^^'; // characters used to separate the user name and date-time
$vst_id = '-vst-'; // an identifier to know that it is a visitor, not logged user
/*
If you have an user registration script,
replace $_SESSION['nume'] with the variable in which the user name is stored.
You can get a free registration script from: http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/
// get the user name if it is logged, or the visitors IP (and add the identifier)
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i'; // regexp to recognize the line with visitors
$nrvst = 0; // to store the number of visitors
// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)
$addrow[] = $uvon. $sep. time();
// check if the file from $filetxt exists and is writable
if(is_writable($filetxt)) {
// get into an array the lines added in $filetxt
$ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nrrows = count($ar_rows);
// number of rows
// if there is at least one line, parse the $ar_rows array
if($nrrows>0) {
for($i=0; $i<$nrrows; $i++) {
// get each line and separate the user /visitor and the timestamp
$ar_line = explode($sep, $ar_rows[$i]);
// add in $addrow array the records in last $timeon seconds
if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
$addrow[] = $ar_rows[$i];
}
}
}
}
$nruvon = count($addrow); // total online
$usron = ''; // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
if(preg_match($rgxvst, $addrow[$i])) $nrvst++; // increment the visitors
else {
// gets and stores the user name
$ar_usron = explode($sep, $addrow[$i]);
$usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
}
}
$nrusr = $nruvon - $nrvst; // gets the users (total - visitors)
// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';
// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';
// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";
echo $reout; // output /display the result
?>
3. Если вы хотите включить script выше в файл .php, добавьте следующий код в том месте, где вы хотите показать количество онлайн-пользователей и посетителей:
4 - Чтобы показать количество онлайн-посетителей/пользователей в файле .html, используйте этот код:
<script type="text/javascript" src="usersontxt.php?uvon=showon"></script>
Этот script (и другой представленный ниже) работает с $_SESSION. В начале файла PHP, в котором вы его используете, вы должны добавить: session_start();. Count Online пользователей и посетителей, использующих таблицу MySQL
Чтобы регистрировать, подсчитывать и показывать количество посетителей и пользователей онлайн в таблице MySQL, необходимо выполнить три SQL-запроса: Удалите записи старше определенного времени. Вставьте строку с новым пользователем/посетителем или, если она уже вставлена, обновите метку времени в ее столбце. Выберите оставшиеся строки. Здесь код для script, который использует таблицу MySQL (с именем "userson" ) для хранения и отображения онлайн-пользователей и посетителей.
1-Сначала мы создаем таблицу "userson" с двумя столбцами (uvon, dt). В столбце "uvon" хранится имя пользователя (при входе в систему) или IP-адрес посетителя. В столбце "dt" хранится номер с временной меткой (время Unix) при доступе к странице. - Добавьте следующий код в php файл (например, с именем "create_userson.php" ): Код для create_userson.php
<?php
header('Content-type: text/html; charset=utf-8');
// HERE add your data for connecting to MySQ database
$host = 'localhost'; // MySQL server address
$user = 'root'; // User name
$pass = 'password'; // User`s password
$dbname = 'database'; // Database name
// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);
// check connection
if (mysqli_connect_errno()) exit('Connect failed: '. mysqli_connect_error());
// sql query for CREATE "userson" TABLE
$sql = "CREATE TABLE `userson` (
`uvon` VARCHAR(32) PRIMARY KEY,
`dt` INT(10) UNSIGNED NOT NULL
) CHARACTER SET utf8 COLLATE utf8_general_ci";
// Performs the $sql query on the server to create the table
if ($conn->query($sql) === TRUE) echo 'Table "userson" successfully created';
else echo 'Error: '. $conn->error;
$conn->close();
?>
2. - Now we create the script that Inserts, Deletes, and Selects data in the "userson" table (For explanations about the code, see the comments in script).
- Add the code below in another php file (named "usersmysql.php"):
In both file you must add your personal data for connecting to MySQL database, in the variables: $host, $user, $pass, and $dbname .
The code for usersmysql.php
<?php
// Script Online Users and Visitors - coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start(); // start Session, if not already started
// HERE add your data for connecting to MySQ database
$host = 'localhost'; // MySQL server address
$user = 'root'; // User name
$pass = 'password'; // User`s password
$dbname = 'database'; // Database name
/*
If you have an user registration script,
replace $_SESSION['nume'] with the variable in which the user name is stored.
You can get a free registration script from: http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/
// get the user name if it is logged, or the visitors IP (and add the identifier)
$vst_id = '-vst-'; // an identifier to know that it is a visitor, not logged user
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i'; // regexp to recognize the rows with visitors
$dt = time(); // current timestamp
$timeon = 120; // number of secconds to keep a user online
$nrvst = 0; // to store the number of visitors
$nrusr = 0; // to store the number of usersrs
$usron = ''; // to store the name of logged users
// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);
// Define and execute the Delete, Insert/Update, and Select queries
$sqldel = "DELETE FROM `userson` WHERE `dt`<". ($dt - $timeon);
$sqliu = "INSERT INTO `userson` (`uvon`, `dt`) VALUES ('$uvon', $dt) ON DUPLICATE KEY UPDATE `dt`=$dt";
$sqlsel = "SELECT * FROM `userson`";
// Execute each query
if(!$conn->query($sqldel)) echo 'Error: '. $conn->error;
if(!$conn->query($sqliu)) echo 'Error: '. $conn->error;
$result = $conn->query($sqlsel);
// if the $result contains at least one row
if ($result->num_rows > 0) {
// traverse the sets of results and set the number of online visitors and users ($nrvst, $nrusr)
while($row = $result->fetch_assoc()) {
if(preg_match($rgxvst, $row['uvon'])) $nrvst++; // increment the visitors
else {
$nrusr++; // increment the users
$usron .= '<br/> - <i>'.$row['uvon']. '</i>'; // stores the user name
}
}
}
$conn->close(); // close the MySQL connection
// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. ($nrusr+$nrvst). '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';
// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";
echo $reout; // output /display the result
?>
- После того, как вы создали эти два php файла на своем сервере, запустите "create_userson.php" в вашем браузере, чтобы создать таблицу "userson" .
- Включите файл usersmysql.php в php файл, в котором вы хотите отобразить количество пользователей и посетителей онлайн.
- Или, если вы хотите вставить его в файл .html, добавьте этот код:
Примеры, использующие эти сценарии
• Включая "usersontxt.php" в php файл:
Счетчик онлайн-пользователей и посетителей
• Включая "usersmysql.php" в html файл: Счетчик онлайн-пользователей и посетителей
Оба сценария (с сохранением данных в текстовом файле на сервере или в таблице MySQL) будут отображаться следующим образом: В сети: 5
Посетителей: 3 Пользователи: 2 - MarPlo - Мариус