Mysql
 sql >> Database >  >> RDS >> Mysql

Come faccio a contare i visitatori unici del mio sito?

Ecco un bel tutorial, è quello che ti serve.(Fonte: corsiweb.net/php-mysql )

Registrati e mostra utenti e visitatori online

Conta utenti e visitatori online utilizzando una tabella MySQL

In questo tutorial puoi imparare come registrarti, contare e visualizzare nella tua pagina web il numero di utenti e visitatori online. Il principio è questo:ogni utente/visitatore è registrato in un file di testo o database. Ogni volta che si accede a una pagina del sito web, lo script php cancella tutti i record più vecchi di un certo tempo (es. 2 minuti), aggiunge l'utente/visitatore corrente e prende il numero di record rimasti da visualizzare.

Puoi archiviare utenti e visitatori online in un file sul server o in una tabella MySQL. In questo caso, penso che l'utilizzo di un file di testo per aggiungere e leggere i record sia più veloce che archiviarli in una tabella MySQL, che richiede più richieste.

Per prima cosa viene presentato il metodo con registrazione in un file di testo sul server, quindi il metodo con tabella MySQL.

Per scaricare i file con gli script presentati in questo tutorial, fare clic su -> Count Online Utenti e Visitatori .

• Entrambi gli script possono essere inclusi nei file ".php" (con include() ) o in " .html" file (con <script> ) , come puoi vedere negli esempi presentati in fondo a questa pagina; ma il server deve eseguire PHP.

Memorizzazione di utenti e visitatori online in un file di testo

Per aggiungere record in un file sul server con PHP devi impostare i permessi CHMOD 0766 (o CHMOD 0777) su quel file, in modo che il PHP possa scrivervi dati.

  1. Crea un file di testo sul tuo server (ad esempio, denominato userson.txt ) e dargli CHMOD 0777 autorizzazioni (nella tua applicazione FTP, fai clic con il pulsante destro del mouse su quel file, scegli Proprietà, quindi seleziona Read , Write e Execute opzioni).
  2. Crea un file PHP (denominato usersontxt.php ) con il codice seguente, quindi copia questo file php nella stessa directory di userson.txt .

Il codice per 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. Se vuoi includere lo script sopra in un file ".php", aggiungi il seguente codice nel punto in cui vuoi mostrare il numero di utenti e visitatori online:

4.Per mostrare il numero di visitatori/utenti online in un file ".html", utilizzare questo codice:

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

Questo script (e l'altro presentato di seguito) funziona con $_SESSION. All'inizio del file PHP in cui lo utilizzi, devi aggiungere:session_start();.Count Utenti e visitatori online che utilizzano una tabella MySQL

Per registrarsi, contare e mostrare il numero di visitatori e utenti online in una tabella MySQL, è necessario eseguire tre query SQL:Elimina i record più vecchi di un certo tempo. Inserisci una riga con il nuovo utente/visitatore, oppure, se è già inserito, Aggiorna il timestamp nella sua colonna.Seleziona le righe rimanenti.Ecco il codice per uno script che utilizza una tabella MySQL (denominata "userson") per memorizzare e visualizzare Utenti e Visitatori online.

  1. Prima creiamo la tabella "userson", con 2 colonne (uvon, dt). Nella colonna "uvon" è memorizzato il nome dell'utente (se loggato) o l'IP del visitatore. Nella colonna "dt" è memorizzato un numero con il timestamp (tempo Unix) di accesso alla pagina.
  • Aggiungi il seguente codice in un file php (ad esempio, denominato "create_userson.php"):

Il codice per 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. Ora creiamo lo script che inserisce, elimina e seleziona i dati nel userson tabella (Per spiegazioni sul codice, vedere i commenti nello script).
  • Aggiungi il codice qui sotto in un altro file php (denominato usersmysql.php ):In entrambi i file devi aggiungere i tuoi dati personali per la connessione al database MySQL, nelle variabili:$host , $user , $pass e $dbname .

Il codice per 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. Dopo aver creato questi due file php sul tuo server, esegui "create_userson.php" sul tuo browser per creare la tabella "userson".

  2. Includi usersmysql.php nel file php in cui vuoi visualizzare il numero di utenti e visitatori online.

  3. Oppure, se vuoi inserirlo in un file ".html", aggiungi questo codice:

Esempi che utilizzano questi script

• Includere "usersontxt.php` in un file php:

Contatore utenti e visitatori online

• Includere "usersmysql.php" in un 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>

Entrambi gli script (con la memorizzazione dei dati in un file di testo sul server o in una tabella MySQL) visualizzeranno un risultato come questo:Online:5

Visitatori:3Utenti:2

  • MarPlo
  • Mario