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­re­sen­ta­tion­al purpose, many website operators also use the dis­cov­ered visitor numbers for web analytics. Most rely on the in­te­grat­ed web counter pos­si­bil­i­ties 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 JavaScript ap­pli­ca­tions, which record specific in­for­ma­tion about in­di­vid­ual 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.

$1 Domain Names – Register yours today!
  • Simple reg­is­tra­tion
  • Premium TLDs at great prices
  • 24/7 personal con­sul­tant included
  • Free privacy pro­tec­tion for eligible domains

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

The easiest way to integrate a counter onto your website is un­doubt­ed­ly by down­load­ing a finished script. Fee-based and free visitor counters are primarily separated by their per­for­mance range. If you decide on a paid version, you usually will also receive visually prepared sta­tis­tics with in­for­ma­tion that goes far beyond the mere traffic stats. How detailed these pieces of in­for­ma­tion art depends on whether recording visitor ac­tiv­i­ties happens solely on the server side, or on the client side as well. In both cases, though, the following standard pa­ra­me­ters are included:

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

Depending on the con­fig­u­ra­tion, the server can assign a unique iden­ti­fi­er (session cookie) to each in­di­vid­ual visitor on their first access. In the visitor counter sta­tis­tics, 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 in­for­ma­tion gathered. For example, tracking reveals which operating systems and which browser ex­ten­sions the visitor used, or what screen res­o­lu­tion is set. The latter set of in­for­ma­tion can play a critical role in website op­ti­miza­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­spec­tive tool. This snippet is then in­te­grat­ed 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 sta­tis­tics. 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­for­ma­tion on a database like MySQL. Before we go into the actual script, we’ll quickly discuss the cor­re­spond­ing database con­fig­u­ra­tion in the next section.

Configure MySQL database for web counters

Joining with a database is generally as­so­ci­at­ed with more requests, and so is more complex than re­triev­ing the in­for­ma­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­nec­es­sar­i­ly. Depending on which in­for­ma­tion you want to record and evaluate with your visitor counter, you need to create a table with a cor­re­spond­ing number of fields. Four fields (four pieces of in­for­ma­tion) are of par­tic­u­lar interest:

  • id: It’s rec­om­mend­ed to set the ‘id’ field in the first spot on your created table, which is used for clar­i­fi­ca­tion and easier handling of data records (for example, if the entries are to be sorted). The use of this field is rec­om­mend­ed, but it’s not required. In order for the database to se­quen­tial­ly number later entries, and to assign each number only once, specify the pa­ra­me­ters AUTO_INCREMENT and PRIMARY KEY.
  • access_page: The ‘access­_page’ column is always required. It’s des­ig­nat­ed for the title of the re­spec­tive website where the visitor counter is in­te­grat­ed. With the pa­ra­me­ters 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 au­to­mat­i­cal­ly 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 au­to­mat­i­cal­ly 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­re­spond­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 pre­sen­ta­tion on the homepage.

Since the complete script is quite complex, the following sections deal with each of the in­di­vid­ual 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 pa­ra­me­ters for ini­tial­iz­ing the database – server and pro­pri­etor 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­re­spond­ing lines for filling the database. The ‘INSERT … ON DUPLICATE KEY UPDATE’ statement used in com­bi­na­tion with the in­te­grat­ed 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­re­spond­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­vid­ual 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­te­grat­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­re­spond­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 we­b­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­te­grat­ed 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­re­spond­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­re­spond­ing entry already exists, then the counter in the database is only increased by 1.

Pre­sent­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 au­to­mat­i­cal­ly 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