Visitor counter: Create a counter for your website

Visitor counters keep track of how often a website is accessed, and usually display the number of visitors at the bottom of the homepage. While the visual output of the user data generally only serves a representational purpose, many website operators also use the discovered visitor numbers for web analytics. Most rely on the integrated web counter possibilities from content management systems or homepage building sets for this, or purchase a counter from one of the various online providers. These solutions commonly use the counter pixels known from logfile analysis or similar JavaScript applications, which record specific information about individual users as well as the number of visitors.

So that you’re not dependent on an external service provider, and to stay on the safe side with your privacy protection, you can choose to create your own visitor counter instead, and run it on your own web space. You just need a database or text file, as well as basic PHP know-how.

How do downloadable web counter solutions work?

The easiest way to integrate a counter onto your website is undoubtedly by downloading a finished script. Fee-based and free visitor counters are primarily separated by their performance range. If you decide on a paid version, you usually will also receive visually prepared statistics with information that goes far beyond the mere traffic stats. How detailed these pieces of information art depends on whether recording visitor activities happens solely on the server side, or on the client side as well. In both cases, though, the following standard parameters are included:

  • Time of access
  • IP address of the visitor
  • Client of the visitor
  • Source URL

Depending on the configuration, the server can assign a unique identifier (session cookie) to each individual visitor on their first access. In the visitor counter statistics, you can observe whether it’s the first page visit for a user, or if they’ve accessed multiple pages. With the help of JavaScript or Adobe Flash on the client side, you can also increase the amount of information gathered. For example, tracking reveals which operating systems and which browser extensions the visitor used, or what screen resolution is set. The latter set of information can play a critical role in website optimisation for mobile devices, for instance.

With most providers, you can decide between various designs and sizes for the visitor counter to be displayed later. Simply choose one of the available designs and your desired size, and generate an HTML code with a click via the respective tool. This snippet is then integrated in the chosen spot on your web page to activate the visitor tracking.

Create your own visitor counter – a tutorial

If you want to create your own visitor counter for your homepage, you need to first make the appropriate structures. For example, the recorded access first needs to be saved. Only then can the counter later display the current status and provide meaningful statistics. For smaller websites, a simple text file can do the job, placed on your server with its location specified in the script. The bigger your web project and the higher the average traffic, though, the sooner you should make the switch and start saving your information on a database like MySQL. Before we go into the actual script, we’ll quickly discuss the corresponding database configuration in the next section.

Configure MySQL database for web counters

Joining with a database is generally associated with more requests, and so is more complex than retrieving the information from a simple text file. You should check in advance whether using MySQL and co. is worthwhile for you, or you may slow down your project unnecessarily. Depending on which information you want to record and evaluate with your visitor counter, you need to create a table with a corresponding number of fields. Four fields (four pieces of information) are of particular interest:

  • id: It’s recommended to set the ‘id’ field in the first spot on your created table, which is used for clarification and easier handling of data records (for example, if the entries are to be sorted). The use of this field is recommended, but it’s not required. In order for the database to sequentially number later entries, and to assign each number only once, specify the parameters AUTO_INCREMENT and PRIMARY KEY.
  • access_page: The ‘access­_page’ column is always required. It’s designated for the title of the respective website where the visitor counter is integrated. With the parameters NOT NULL and UNIQUE, you can also make sure that no double entries will be displayed. You can use either VARCHAR or TEXT as the data type for this field.
  • access_counter: The actual visitor counter for the HTML pages hides behind the INTEGER field ‘access_counter’. Each time the ‘access_page’ is accessed, the value is automatically increased by 1.
  • access_date: The time stamp for the site access doesn’t have to be stored in the database, but it’s usually one of the first values collected by a web counter. Using the data type TIMESTAMP along with the attribute CURRENT_TIMESTAMP gives you the current entries, which contain the data as well as the exact time. Enter the rule ON UPDATE CURRENT_TIMESTAMP as well to automatically enter the time stamp into the database without requiring further programming on your side.

Create the appropriate visitor counter PHP function

The scripting language PHP is perfectly suited for transferring visitor data to the database and reading out the date required for the counter. For this, the corresponding script has to contain one function that fulfills the following three requirements:

  1. It needs to be linked to the database and be able to open it.

  2. It needs to check the table to see if a specified record already exists, and then either increase its access counter by 1 or create a new data set with a value of 1.

  3. It needs to return the current value of the visitor counter for presentation on the homepage.

Since the complete script is quite complex, the following sections deal with each of the individual sub-steps of the function on their own. In this tutorial, the function is named ‘visitor’.

The visitor counter PHP code starts with the necessary parameters for initialising the database – server and proprietor of the database, its password and log-in name, as well as the correct spelling of the table and the required mandatory fields (such as access_page). It’s important that the correct data is entered here so that a connection to the database can be made later.

<?php
function visitor($record) {
  $db_host = "localhost";
  $db_username = "username"; 
  $db_password = "password";
  $db_name = "database-name";
  $db_table = "table-name";
  $counter_page = "access_page";
  $counter_field = "access_counter";

Next is the instruction used to open the database or issue an error message if the connection fails:

$db = mysqli_connect($db_host, $db_username, $db_password, $db_name) or die("Host not accessible");
$db = mysql_select_db ($db_name, $link) or die("Database not accessible");

After these entries, the PHP script has to be extended by the corresponding lines for filling the database. The ‘INSERT … ON DUPLICATE KEY UPDATE’ statement used in combination with the integrated increase of the field value by 1 is crucial for making sure that the counter is updated as desired if a data set already exists:

$sql_call = "INSERT INTO ".$db_table." (".$counter_page.", ".$counter_field.") VALUES ('".$record."', 1) ON DUPLICATE KEY UPDATE ".$counter_field." = ".$counter_field." + 1"; 
mysqli_query($db, $sql_call) or die("Error while entering");

With this, the function already fulfills two of the three defined tasks: It provides the connection to the database as well as the following creation of the data records or updating of existing data records. Because the script still needs to fulfill a third requirement to return the current status of the website’s visitor counter, you now need to add a corresponding database query (mysql_query) and define the numerical output of the results (mysql_fetch_assoc). In the last step, the function should close the database and give back the result via return, so the final part of the function goes as follows:

$sql_call = "SELECT ".$counter_field. " FROM ".$db_table." WHERE ".$counter_page. " = '".$record. "'";
$sql_result = mysqli_query($db, $sql_call) or die("SQL request failed");
$row = mysqli_fetch_assoc($sql_result);
$x = $row[$counter_field];

mysqli_close($db);
return $x;
  }
?>

How the finished PHP script looks

After the individual parts of the PHP function have been explained in the previous sections, this section will now present the complete script that allows you to add a free visitor counter to your homepage.

<?php
function visitor($record) {
  $db_host = "localhost";
  $db_username = "username"; 
  $db_password = "password";
  $db_name = "database-name";
  $db_table = "table-name";
  $counter_page = "access_page";
  $counter_field = "access_counter";

  $db = mysqli_connect ($db_host, $db_username, $db_password, $db_name) or die("Host or database not accessible");

  $sql_call = "INSERT INTO ".$db_table." (".$counter_page.", ".$counter_field.") VALUES ('".$record."', 1) ON DUPLICATE KEY UPDATE ".$counter_field." = ".$counter_field." + 1"; 
  mysqli_query($db, $sql_call) or die("Error while entering");

$sql_call = "SELECT ".$counter_field. " FROM ".$db_table." WHERE ".$counter_page. " = '".$record. "'";
$sql_result = mysqli_query($db, $sql_call) or die("SQL request failed ");
$row = mysqli_fetch_assoc($sql_result);
$x = $row[$counter_field];

mysqli_close($db);
return $x;
  }
?>

Integrating the script in the HTML documents

If you want to integrate your own completed PHP visitor counter into your website, then you have to make a few small changes to the corresponding HTML document. The most important update is swapping the existing .html extension with the .php extension. You should also assign a meaningful name to the PHP variable $page_name in the page’s headline:

<?php
  $page_name = "Unique page name";
?>

With the help of the PHP function echo you can also make the chosen page name, which is later included in the access_page field of the database, be the page title:

<title><?php echo $page_name; ?></title>

To integrate the visitor counter script – in this example called webcounter.php – you’ll now enter the PHP command include in the desired position on your website. In the same step, you’ll also pass the contents of the $page_name variable to the ‘visitor()’ function:

<?php
include "webcounter.php";
$access_number = visitor($page_name);
?>

As soon as this code has been integrated into the page, your PHP script will take effect: If the page title (the content of $page_name) isn’t already present in the database table, it ensures that a corresponding data set is created. The access_counter field adopts a value of 1 and the function then tells the site when access has occurred. If a corresponding entry already exists, then the counter in the database is only increased by 1.

Presenting the visitor count on the homepage

After you’ve created your visitor counter and started recording the traffic of your visitors, you can also display the current counter status directly on your website. The simplest way, for example, is via an announcement which is automatically displayed in the page’s footer. For this, you only need a footer element. Using the echo command, enter the current value of the variable $access_number into the text:

< footer>
  <p>
<?php
    echo "You are the", $access_number, " visitor on this site!";
    ?>
</p>
</footer>