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 rep­res­ent­a­tion­al purpose, many website operators also use the dis­covered visitor numbers for web analytics. Most rely on the in­teg­rated web counter pos­sib­il­it­ies from content man­age­ment 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 JavaS­cript ap­plic­a­tions, which record specific in­form­a­tion about in­di­vidu­al 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 pro­tec­tion, 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.

Cheap domain names – buy yours now
  • Free website pro­tec­tion with SSL Wildcard included
  • Free private re­gis­tra­tion for greater privacy
  • Free Domain Connect for easy DNS setup

How do down­load­able web counter solutions work?

The easiest way to integrate a counter onto your website is un­doubtedly by down­load­ing a finished script. Fee-based and free visitor counters are primarily separated by their per­form­ance range. If you decide on a paid version, you usually will also receive visually prepared stat­ist­ics with in­form­a­tion that goes far beyond the mere traffic stats. How detailed these pieces of in­form­a­tion art depends on whether recording visitor activ­it­ies happens solely on the server side, or on the client side as well. In both cases, though, the following standard para­met­ers are included:

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

Depending on the con­fig­ur­a­tion, the server can assign a unique iden­ti­fi­er (session cookie) to each in­di­vidu­al visitor on their first access. In the visitor counter stat­ist­ics, you can observe whether it’s the first page visit for a user, or if they’ve accessed multiple pages. With the help of JavaS­cript or Adobe Flash on the client side, you can also increase the amount of in­form­a­tion gathered. For example, tracking reveals which operating systems and which browser ex­ten­sions the visitor used, or what screen res­ol­u­tion is set. The latter set of in­form­a­tion can play a critical role in website op­tim­isa­tion 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 re­spect­ive tool. This snippet is then in­teg­rated 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 ap­pro­pri­ate struc­tures. For example, the recorded access first needs to be saved. Only then can the counter later display the current status and provide mean­ing­ful stat­ist­ics. 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 in­form­a­tion on a database like MySQL. Before we go into the actual script, we’ll quickly discuss the cor­res­pond­ing database con­fig­ur­a­tion in the next section.

Configure MySQL database for web counters

Joining with a database is generally as­so­ci­ated with more requests, and so is more complex than re­triev­ing the in­form­a­tion from a simple text file. You should check in advance whether using MySQL and co. is worth­while for you, or you may slow down your project un­ne­ces­sar­ily. Depending on which in­form­a­tion you want to record and evaluate with your visitor counter, you need to create a table with a cor­res­pond­ing number of fields. Four fields (four pieces of in­form­a­tion) are of par­tic­u­lar interest:

  • id: It’s re­com­men­ded to set the ‘id’ field in the first spot on your created table, which is used for cla­ri­fic­a­tion and easier handling of data records (for example, if the entries are to be sorted). The use of this field is re­com­men­ded, but it’s not required. In order for the database to se­quen­tially number later entries, and to assign each number only once, specify the para­met­ers AUTO_INCREMENT and PRIMARY KEY.
  • access_page: The ‘access­_page’ column is always required. It’s des­ig­nated for the title of the re­spect­ive website where the visitor counter is in­teg­rated. With the para­met­ers 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 auto­mat­ic­ally 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 auto­mat­ic­ally enter the time stamp into the database without requiring further pro­gram­ming on your side.

Create the ap­pro­pri­ate visitor counter PHP function

The scripting language PHP is perfectly suited for trans­fer­ring visitor data to the database and reading out the date required for the counter. For this, the cor­res­pond­ing script has to contain one function that fulfills the following three re­quire­ments:

  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 present­a­tion on the homepage.

Since the complete script is quite complex, the following sections deal with each of the in­di­vidu­al 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 para­met­ers for ini­tial­ising the database – server and pro­pri­et­or 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 con­nec­tion 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 in­struc­tion used to open the database or issue an error message if the con­nec­tion 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 cor­res­pond­ing lines for filling the database. The ‘INSERT … ON DUPLICATE KEY UPDATE’ statement used in com­bin­a­tion with the in­teg­rated 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 con­nec­tion 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 re­quire­ment to return the current status of the website’s visitor counter, you now need to add a cor­res­pond­ing 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 in­di­vidu­al 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;
    }
?>

In­teg­rat­ing 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 cor­res­pond­ing HTML document. The most important update is swapping the existing .html extension with the .php extension. You should also assign a mean­ing­ful 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 web­counter.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 in­teg­rated 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 cor­res­pond­ing 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 cor­res­pond­ing entry already exists, then the counter in the database is only increased by 1.

Present­ing 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 an­nounce­ment which is auto­mat­ic­ally 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>
Go to Main Menu