This tutorial presents a Class that can be used to store and to count the number of accesses of files.
It can be used especially to counts the number of downloads.
This class, named CountAccess connects to a MySQL database with the PHP mysqli extension. It has three methods and Constructor:

- For more detailed explanations about the PHP instructions used in CountAccess class, see the comments inside class.

The CountAccess class

• Also, you can downlod this class (with a test file) from: CountAccess class
// - CountAccess class ( )
// stores and counts the number of accesses

class CountAccess {
  // define public properties for table name and its columns
  public $tb_name = 'access';
  public $tb_cols = array('urlf'=>'urlf', 'nrac'=>'nrac', 'dt'=>'dt');

  // protected property to store the connection to the MySQL server
  protected $conn;

  // Constructor
  public function __construct($server, $user, $pass, $db) {
    // create the connection to MySQL database (stores it in $conn property)
    $this->conn = new mysqli($server, $user, $pass, $db);
    if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit; }

    // check if table $tb_name exists in $db
    // if not exists, calls the setTable() method to create the table
    $Tables_in_db = 'Tables_in_'.$db;
    if($result=$this->conn->query("SHOW TABLES IN $db WHERE `$Tables_in_db` = '$this->tb_name'")) {
      if(mysqli_num_rows($result)<=0) {

  // method used to create the table
  private function setTable() {
    // sql query for CREATE TABLE
    $sql = "CREATE TABLE `$this->tb_name` (
     `". $this->tb_cols['urlf']. "`  VARCHAR(88) PRIMARY KEY NOT NULL,
     `". $this->tb_cols['nrac']. "` INT(8) UNSIGNED DEFAULT 1,
     `". $this->tb_cols['dt']. "` TIMESTAMP
    ) CHARACTER SET utf8 COLLATE utf8_general_ci";

    // performs the $sql query on the server to create the table, on failure returns the error
    if (!$this->conn->query($sql) === TRUE) {
      echo 'Error create table: '. $this->conn->error;

  // method to insert / update the number of accesses of $urlf
  public function setAccess($urlf) {
    $urlf = $this->conn->real_escape_string($urlf);       // escape special characters for use in the SQL query

    // sql query for INSERT / UPDATE
    $sql = "INSERT INTO `". $this->tb_name. "` (`". $this->tb_cols['urlf']. "`) VALUES ('$urlf') ON DUPLICATE KEY UPDATE `". $this->tb_cols['nrac']. "`=`". $this->tb_cols['nrac']. "`+1";

    // performs the $sql query on the server to insert / update the values
    if (!$this->conn->query($sql) === TRUE) {
      echo 'Error: '. $this->conn->error;

  // method to select the number of accesses (and the date-time of the last accessing) of $urlf
  public function getAccess($urlf) {
    $urlf = $this->conn->real_escape_string($urlf);       // escape special characters for use in the SQL query

    // sql query for SELECT
    $sql = "SELECT `". $this->tb_cols['nrac']. "`, DATE_FORMAT(`". $this->tb_cols['dt']. "`, '%d-%m-%Y %H:%i') AS dt FROM `". $this->tb_name. "` WHERE `". $this->tb_cols['urlf']. "`='$urlf' LIMIT 1";

    // perform the query and store the results
    $result = $this->conn->query($sql);

    // if the $result contains at least one row
    if ($result->num_rows > 0) {
      // store the number of accesses and the date-time in a array
      while($row = $result->fetch_assoc()) {
        $re = 'Accesses: '. $row['nrac']. ', last: <i>'. $row['dt']. '</i>';
    else { $re = 'Accesses: 0, last: 0'; }

    // closes the statement, to free the memory

    return $re;          // returns the string from $re

      /* Using the CountAccess class  */

// sets data for connecting to mysql database (server_address, username, password and database_name)
$server = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'db_name';

// create the MySQL connection and a instance of CountAccess class
$objCA = new CountAccess($server, $user, $pass, $db);

// if there is $_GET['urlf']
if (isset($_GET['urlf'])) {
  $urlf = trim(strip_tags($_GET['urlf']));        // delete tags and white spaces

  // calls the setAccess() method to insert / update the number of accesses

  // Redirects the browser to the URL stored in $urlf
  header("Location: " . $urlf); exit;

How to use the CountAccess class

1. Copy the code above in a PHP file (for example "class.CountAccess.php") on your server.
2. In this code, change the values of the $server, $user, $pass and $db variables, with your data for connecting to MySQL database. These variables are located after the line with "/* Using the CountAccess class */".
3. Build the download links whose number of accesses you want to count with the following form:
<a href="path/class.CountAccess.php?urlf=dir/" title="Download title">Download</a>
    - "path/class.CountAccess.php" - is the path to the PHP file with the CountAccess class.
    - "dir/" - is the path and the name of the file for download.

4. In the PHP page where you want to show the number of accesses, include this class (with include('class.CountAccess.php'); ).
Then, call the echo $objCA->getAccess($urlf);, where $urlf is the path and name of the file for download, the same with the address (or name) added in the "href" attribute, after the "urlf=".
                For example:     echo $objCA->getAccess('dir/');

The next example shows a PHP page which use the CountAccess class for two download links:
// include the file with CountAccess class
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "" >
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Count Downloads</title>

<!-- The Download links, via the class.CountAccess.php file -->
<a href="class.CountAccess.php?urlf=download/" title="Download test">Download Test</a> - 
<?php echo $objCA->getAccess('download/'); ?>
<br />
<a href="class.CountAccess.php?" title="Download Smile">Download Smile</a> - 
<?php echo $objCA->getAccess(''); ?>

This code will dislay something like:


Download Test - Accesses: 2, last: 21-04-2011 15:13
Download Smile - Accesses: 3, last: 21-04-2011 15:21
- The string which shows the number of accesses (downloads) can be modified from the getAccess() method, in CountAccess class.
- The date-time format can be changed in the getAccess() method, to the instruction "... DATE_FORMAT(`". $this->tb_cols['dt']. "`, '%d-%m-%Y %H:%i') ...", change the ('%d-%m-%Y %H:%i'), if you know how to.

• This class can be used to store, to count and display the number of accesses of any element (by a name, a URL, etc.).
    - Include the class in the PHP file in which you want to use it.
    - To insert / update the number of accesses, calls the method:   $objCA->setAccess('name');
    - To display the number of accesses and the date-time of last accessing, call:   echo $objCA->getAccess('name');
// include the file with CountAccess class

$name = 'a_string_value';
$objCA->setAccess($name);            // insert / update the number of accesses for $name
echo $objCA->getAccess($name);       // output the number of accesses and date-time

Daily Test with Code Example

Which attribute is used in <a> tag for the address of the link?
src href rel
<a href="" title=""></a>
Which CSS property sets the type of the text font?
font-family text-decoration font-size
h2 {
What instruction selects all the <div> tags with class="cls"?
querySelector("div.cls") getElementsByTagName("div") querySelectorAll("div.cls")
var elm_list = document.querySelectorAll("div.cls");
var nr_elms = elm_list.length;       // number of selected items
Indicate the function that can be used to get the sum of values in an array.
array_sum() array_diff() array_shift()
$arr = array(1, 2, 3, 4);
$arr_sum = array_sum($arr);
echo $arr_sum;       // 10
Count the number of downloads and accesses

Last accessed pages

  1. Skill Games (3913)
  2. Mahjong Games (13787)
  3. Select the Content of HTML Element (1807)
  4. Mahjong Gardens (4150)
  5. Escape Games (5820)

Popular pages this month

  1. Qwop (4763)
  2. Bubbles3 (4404)
  3. Butterfly Kyodai (3133)
  4. Zuma Deluxe (2904)
  5. Backgammon (1486)