How to Count Unique Visitors to My Site

How do I count unique visitors to my site?

Here is a nice tutorial, it is what you need.
(Source: coursesweb.net/php-mysql)

Register and show online users and visitors

Count Online users and visitors using a MySQL table

In this tutorial you can learn how to register, to count, and display in your webpage the number of online users and visitors.
The principle is this: each user / visitor is registered in a text file or database. Every time a page of the website is accessed, the php script deletes all records older than a certain time (eg 2 minutes), adds the current user / visitor and takes the number of records left to display.

You can store the online users and visitors in a file on the server, or in a MySQL table.
In this case, I think that using a text file to add and read the records is faster than storing them into a MySQL table, which requires more requests.

First it's presented the method with recording in a text file on the server, than the method with MySQL table.

To download the files with the scripts presented in this tutorial, click -> Count Online Users and Visitors.

• Both scripts can be included in ".php" files (with include()), or in ".html" files (with <script>), as you can see in the examples presented at the bottom of this page; but the server must run PHP.

Storing online users and visitors in a text file

To add records in a file on the server with PHP you must set CHMOD 0766 (or CHMOD 0777) permissions to that file, so the PHP can write data in it.

  1. Create a text file on your server (for example, named userson.txt) and give it CHMOD 0777 permissions (in your FTP application, right click on that file, choose Properties, then select Read, Write, and Execute options).
  2. Create a PHP file (named usersontxt.php) having the code below, then copy this php file in the same directory as userson.txt.

The code for 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. If you want to include the script above in a ".php" file, add the following code in the place you want to show the number of online users and visitors:

4.To show the number of online visitors /users in a ".html" file, use this code:

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

This script (and the other presented below) works with $_SESSION. At the beginning of the PHP file in which you use it, you must add: session_start();.
Count Online users and visitors using a MySQL table

To register, count and show the number of online visitors and users in a MySQL table, require to perform three SQL queries:
Delete the records older than a certain time.
Insert a row with the new user /visitor, or, if it is already inserted, Update the timestamp in its column.
Select the remaining rows.
Here's the code for a script that uses a MySQL table (named "userson") to store and display the Online Users and Visitors.

  1. First we create the "userson" table, with 2 columns (uvon, dt). In the "uvon" column is stored the name of the user (if logged in) or the visitor's IP. In the "dt" column is stored a number with the timestamp (Unix time) when the page is accessed.
  • Add the following code in a php file (for example, named "create_userson.php"):

The code for 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. 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'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. After you have created these two php files on your server, run the "create_userson.php" on your browser to create the "userson" table.

  2. Include the usersmysql.php file in the php file in which you want to display the number of online users and visitors.


  3. Or, if you want to insert it in a ".html" file, add this code:

Examples using these scripts

• Including the "usersontxt.php` in a php file:

<!doctype html>


Counter Online Users and Visitors

• Including the "usersmysql.php" in a html file:

<!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>

Both scripts (with storing data in a text file on the server, or into a MySQL table) will display a result like this:
Online: 5

Visitors: 3
Users: 2

  • MarPlo
  • Marius

What's the best way to count unique visitors on my webpage?

The expiry time needs to be a timestamp for a specific date/time.

This code give a date in 1970.

strtotime('tomorrow') - time(); // 01/01/1970 11:15:01

So your code was just a bit too complicated, set the cookie expiry time to strtotime('tomorrow') which will give tomorrows date at 00:00:00 i.e. the beginining of tomorrow

This code, run at 28/06/2018 13:40:00 will give:

echo date('d/m/Y H:i:s',strtotime('tomorrow')); // 29/06/2018 00:00:00

Try this instead

function CriakCookieDia(){  
if (!isset($_COOKIE[sha1('visita')])){
setcookie(sha1('visita'), true, strtotime('tomorrow'));
return true;
}else{
return false;
}
}

Can you count unique visitors to a website without server side code?

Like it has been said, you need a third-party tool (like Google Analytics) since any workaround done in the front-end part will be related to the client/browser-side, then you'll lose the tracking if a user changes the device for example.

You can easily install Analytics with some of the available plugins (like gatsby-plugin-google-gtag). This is recommended since under the hood uses gtag.js instead of analytics.js, which is what Google recommends due the last API changes.

To use is just install it by:

npm install gatsby-plugin-google-gtag // or yarn add gatsby-plugin-google-gtag

And add your configurations:

// In your gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-google-gtag`,
options: {
// You can add multiple tracking ids and a pageview event will be fired for all of them.
trackingIds: [
"GA-TRACKING_ID", // Google Analytics / GA
],
// This object gets passed directly to the gtag config command
// This config will be shared across all trackingIds
gtagConfig: {
optimize_id: "OPT_CONTAINER_ID",
anonymize_ip: true,
cookie_expires: 0,
},
// This object is used for configuration specific to this plugin
pluginConfig: {
// Puts tracking script in the head instead of the body
head: false,
// Setting this parameter is also optional
respectDNT: true,
// Avoids sending pageview hits from custom paths
exclude: ["/preview/**", "/do-not-track/me/too/"],
},
},
},
],
}

You can ignore the options you don't need.

How can i count unique visitors on my website?

You could create a session cookie for this. Every time someone connects to your service you check for that cookie and increment the counter if the cookie does not exist yet.

Here's how you define a cookie, let's call it "hasVisited":

HttpCookie aCookie = new HttpCookie("hasVisited");
aCookie.Value = true;
aCookie.Expires = DateTime.Now.AddDays(100);
Response.Cookies.Add(aCookie);

You then read it like this:

if(Request.Cookies["hasVisited"] == null)
{
// increment counter and add cookie for future reference...
}

You could also work with IP and MAC-Addresses (being less reliable due to firewalls etc.). To get the IP of the client use:

var remoteIpAddress = Request.UserHostAddress;

For the MAC address I suggest you look at

http://www.dotnetfunda.com/forums/show/2088/how-to-get-mac-address-of-client-machine

for further information.

How do I count unique visitors to my web page and recount the counter everyday without using database?

<?php

$filename = date("Ymd") . "_counter.txt";
$seenFilename = date("Ymd") . '_seen_ip.txt';

$ips = array();
if (file_exists($seenFilename))
{
$ips = file($seenFilename);
$ips = array_map('trim', $ips);
}

if(!in_array($_SERVER['REMOTE_ADDR'], $ips))
{
$visits = 0;
if (file_exists($filename)) {
$visits = file_get_contents($filename);
}

file_put_contents($filename, ++$visits);
$data = $_SERVER['REMOTE_ADDR'] . PHP_EOL;
$fp = fopen($seenFilename, 'a');
fwrite($fp, $data);
}

?>

This code will create a new file every day and record one count for each unique visit.



Related Topics



Leave a reply



Submit