Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

Bagaimana cara menghitung pengunjung unik ke situs saya?

Ini adalah tutorial yang bagus, inilah yang Anda butuhkan. (Sumber: courseweb.net/php-mysql )

Daftar dan tampilkan pengguna dan pengunjung online

Menghitung pengguna dan pengunjung Online menggunakan tabel MySQL

Dalam tutorial ini Anda dapat mempelajari cara mendaftar, menghitung, dan menampilkan di halaman web Anda jumlah pengguna dan pengunjung online. Prinsipnya adalah:setiap pengguna / pengunjung terdaftar dalam file teks atau database. Setiap kali halaman website diakses, script php menghapus semua record yang lebih lama dari waktu tertentu (misalnya 2 menit), menambahkan pengguna / pengunjung saat ini dan mengambil jumlah record yang tersisa untuk ditampilkan.

Anda dapat menyimpan pengguna dan pengunjung online dalam file di server, atau di tabel MySQL. Dalam hal ini, saya pikir menggunakan file teks untuk menambah dan membaca catatan lebih cepat daripada menyimpannya ke dalam tabel MySQL, yang memerlukan lebih banyak permintaan.

Pertama disajikan metode dengan merekam dalam file teks di server, daripada metode dengan tabel MySQL.

Untuk mengunduh file dengan skrip yang disajikan dalam tutorial ini, klik -> Hitung Online Pengguna dan Pengunjung .

• Kedua skrip dapat dimasukkan dalam file ".php" (dengan include() ) , atau di " .html" file (dengan <script> ) , seperti yang Anda lihat pada contoh yang disajikan di bagian bawah halaman ini; tetapi server harus menjalankan PHP.

Menyimpan pengguna dan pengunjung online dalam file teks

Untuk menambahkan record dalam file di server dengan PHP, Anda harus mengatur izin CHMOD 0766 (atau CHMOD 0777) ke file tersebut, sehingga PHP dapat menulis data di dalamnya.

  1. Buat file teks di server Anda (misalnya, bernama userson.txt ) dan berikan CHMOD 0777 izin (dalam aplikasi FTP Anda, klik kanan pada file itu, pilih Properties, lalu pilih Read , Write , dan Execute pilihan).
  2. Buat file PHP (bernama usersontxt.php ) yang memiliki kode di bawah ini, lalu salin file php ini di direktori yang sama dengan userson.txt .

Kode untuk 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's 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
?>
  1. Jika Anda ingin memasukkan skrip di atas ke dalam file ".php", tambahkan kode berikut di tempat yang Anda inginkan untuk menunjukkan jumlah pengguna dan pengunjung online:

4.Untuk menampilkan jumlah pengunjung/pengguna online dalam file ".html", gunakan kode ini:

<script type="text/javascript" src="usersontxt.php?uvon=showon"></script>

Skrip ini (dan yang lainnya disajikan di bawah) berfungsi dengan $_SESSION. Di awal file PHP tempat Anda menggunakannya, Anda harus menambahkan:session_start();. Hitung pengguna dan pengunjung online menggunakan tabel MySQL

Untuk mendaftar, menghitung, dan menampilkan jumlah pengunjung dan pengguna online di tabel MySQL, perlu melakukan tiga kueri SQL:Hapus catatan yang lebih lama dari waktu tertentu. Sisipkan baris dengan pengguna / pengunjung baru, atau, jika sudah dimasukkan, Perbarui stempel waktu di kolomnya. Pilih baris yang tersisa. Berikut kode untuk skrip yang menggunakan tabel MySQL (bernama "userson") untuk menyimpan dan menampilkan Pengguna dan Pengunjung Online.

  1. Pertama kita buat tabel "userson", dengan 2 kolom (uvon, dt). Pada kolom “uvon” tersimpan nama user (jika login) atau IP pengunjung. Pada kolom “dt” tersimpan sebuah nomor dengan timestamp (waktu Unix) saat halaman diakses.
  • Tambahkan kode berikut dalam file php (misalnya, bernama "create_userson.php"):

Kode untuk 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();
?>
  1. Sekarang kita buat script yang Menyisipkan, Menghapus, dan Memilih data di userson tabel (Untuk penjelasan tentang kode, lihat komentar di skrip).
  • Tambahkan kode di bawah ini di file php lain (bernama usersmysql.php ):Di kedua file Anda harus menambahkan data pribadi Anda untuk menghubungkan ke database MySQL, dalam variabel:$host , $user , $pass , dan $dbname .

Kode untuk 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's 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
?>
  1. Setelah Anda membuat dua file php ini di server Anda, jalankan "create_userson.php" di browser Anda untuk membuat tabel "userson".

  2. Sertakan usersmysql.php file dalam file php di mana Anda ingin menampilkan jumlah pengguna dan pengunjung online.

  3. Atau, jika Anda ingin memasukkannya ke dalam file ".html", tambahkan kode ini:

Contoh menggunakan skrip ini

• Menyertakan "usersontxt.php` dalam file php:

Konter Pengguna dan Pengunjung Online

• Menyertakan "usersmysql.php" dalam file html:

<!doctype html>
<html>
<head>
 <meta charset="utf-8" />
 <title>Counter Online Users and Visitors</title>
 <meta name="description" content="PHP script to count and show the number of online users and visitors" />
 <meta name="keywords" content="online users, online visitors" />
</head>
<body>

<!-- Includes the script ("usersontxt.php", or "usersmysql.php") -->
<script type="text/javascript" src="usersmysql.php?uvon=showon"></script>

</body>
</html>

Kedua skrip (dengan menyimpan data dalam file teks di server, atau ke dalam tabel MySQL) akan menampilkan hasil seperti ini:Online:5

Pengunjung:3Pengguna:2

  • MarPlo
  • Marius


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara yang benar untuk menggunakan LIKE '%{$var}%' dengan pernyataan yang sudah disiapkan? [mysqli]

  2. mysql ke php ke xml menunjukkan usia kosong

  3. MySQL pilih di mana properti bidang JSON memiliki nilai

  4. Menerapkan twitter dan facebook seperti hashtag

  5. Simpan Aksen di Database MySQL