User Tools

Site Tools


web_stats

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
web_stats [2024/05/01 17:57] – created adminweb_stats [2024/05/02 14:21] (current) admin
Line 3: Line 3:
  
 {{wiki:screenshot_small.jpg}} {{wiki:screenshot_small.jpg}}
 +
 +=== Requirments ===
 +  * FTP or SSH access to a web server with PHP support
 +  * <del>A userstack.com API Key for accurate Browser / OS detection</del>
 +  * Visitors to your website / page
 +
 +=== Description / Use ===
 +###
 +The main script is copied over to any web server with PHP support. Drop it into a folder where you are storing your website or web files that you want to monitor. At the very bottom of any pages you want to monitor and before the closing body tag add the following code;
 +###
 +<code>
 +<?php include 'stats.php';?>
 +</code>
 +###
 +Make any required changes in the config section. Then wait for traffic to hit your website / page. The first time this happens the stats viewer namely viewstats.php will be created in the same directory as your web page files. The second time, the log file namely stats.log will be created and the collected visitor data will be added to the top of the file. Subsequent visits will append the log file from the top and when a maximum number of lines is reached the log file is trimmed to keep the size down.
 +###
 +
 +So we end up with //stats.php// (see code below) //stats.log// (the log file) and //viewstats.php// (the nicely formatted log file viewer!)
 +
 +###
 +At the bottom of the viewed statistics table are form buttons to either completely clear the log file or to refresh the page / logs. It's suggested that these are removed / commented out of either the viewer or in the html template section of the script if you do not want any uninvited visitors clearing your logs for you?
 +###
 +
 +=== Demo ===
 +Click [[https://www.cpcnw.co.uk/wiki|here]] to add your hit to this wiki and [[https://www.cpcnw.co.uk/wiki/viewstats.php|here]] to view that hit being logged via the script
 +
 +=== The Code ===
 +<code>
 +<?php
 +/* Simple PHP Web Page Statistics
 +   Log file and viewer created on first run
 +   Call this script by including in web page
 +   <?php include 'stats.php';?>   */
 +
 +// Config Section
 +    define("DATE_FORMAT","d-m-y");
 +    define("TIME_FORMAT","H:i:s");
 +    define("LOG_FILE","stats.log");
 +    define("STATS_FILE","viewstats.php");
 +    define("MAX_RECORDS","20");
 +    define("MY_DOMAIN","domain.com");
 +    define("MY_WANIP","nnn.nnn.nnn.nnn"); // Not included in stats
 +
 +// HTML Template / Style 
 +$statsHtml='
 +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
 +<html><head><title>Stats <?php $viewed=date("d/m/y H:i"); echo $viewed ?></title><style>
 +  table{background:#bbb;border:0px;font-family:"Trebuchet MS",sans-serif;font-size:9pt;}
 +  td{background:#fff; color:#333; padding:5px;}
 +  th{background:#ddd;color:#333;padding:5px;font-family:"Trebuchet MS",sans-serif; font-size:9pt;}
 +  input[type=submit]:hover{color:#FFF;background:#F00;border:none;padding:3px 8px;cursor:pointer;
 +  -webkit-border-radius:3px;border-radius:3px;} form{margin-top:4px;
 +  a:link, visited{text-decoration: none;} a:hover{text-decoration: underline;}
 +  </style></head>
 +<body>
 +  <table cellpadding="0" cellspacing="1">
 +      <tr><th>DATE</th><th>TIME</th><th>IP</th><th>HOSTNAME</th><th>BROWSER</th><th>OS</th><th>ISP</th><th>TIMEZONE</th><th>COUNTRY</th></tr>
 +      <?php include "stats.log";?>
 +      </table>
 +      <form method="post">
 +      <input type="submit" name="delete" value="Clear Log!" title="You Sure?">
 +      <button onclick = "reload()" title="Refresh Stats!" style= "cursor:pointer">Reload</button>
 +      <script>function reload() {
 +              window.localStorage.clear();
 +              location.reload();
 +              } </script>
 +      </form>
 +      <?php
 +        if(isset($_POST["delete"]))
 +          {$file = fopen("stats.log","w");ftruncate($file,0);
 +          fclose($file);}?>
 +      </body></html>';
 +
 +// Local Data Collection
 +    $date = date(DATE_FORMAT);
 +    $time = date(TIME_FORMAT);
 +
 +// Get remote IP address / obfuscate own local IP address
 +    $userIp    = (isset($_SERVER['REMOTE_ADDR']) && ($_SERVER['REMOTE_ADDR'] != ""))  ? $_SERVER['REMOTE_ADDR'] : "Unknown";
 +
 +    if ($userIp != (filter_var($userIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE |  FILTER_FLAG_NO_RES_RANGE))) 
 +       { $publicIp = "Private Address"; $hostName = (MY_DOMAIN); $userIp = (MY_WANIP); }
 +        else 
 +       { $publicIp = $userIp; $hostName  = gethostbyaddr($userIp); }
 +
 +// Get Useragent and Browser       
 +    $userAgent = (isset($_SERVER['HTTP_USER_AGENT']) && ($_SERVER['HTTP_USER_AGENT'] != "")) ? $_SERVER['HTTP_USER_AGENT'] : "Unknown";
 +    $commonBrowsers = ["Opera","OPR/", "Edg", "Chrome", "Safari", "Firefox", "MSIE", "Trident"];
 +    $userBrowser = 'Unknown';
 +    
 +// Operating System
 +    $platform = 'Unknown';
 +     if (preg_match('/linux/i', $userAgent)) 
 +         { $platform = 'Linux'; }
 +      elseif (preg_match('/macintosh|mac os x/i', $userAgent)) 
 +         { $platform = 'Mac'; }
 +      elseif (preg_match('/windows|win32/i', $userAgent)) 
 +         { $platform = 'Windows';
 +         
 +// Users Browser         
 +      foreach ($commonBrowsers as $browser) {
 +         if (strpos($userAgent, $browser) !== false) { $userBrowser = $browser; break; }
 +         }
 +          switch ($userBrowser) {
 +          case 'OPR/': $userBrowser = 'Opera'; break;
 +          case 'MSIE': $userBrowser = 'Internet Explorer'; break;
 +          case 'Trident': $userBrowser = 'Internet Explorer'; break;
 +          case 'Edg': $userBrowser = 'Microsoft Edge'; break;
 +          }
 +                  
 +// Remote Data Collection via http://ip-api.com
 +    $api1 = json_decode(file_get_contents("http://ip-api.com/json/".$userIp."?fields=isp,timezone,countryCode"), true);
 +    $isp = $api1["isp"];
 +    $timezone = $api1["timezone"];
 +    $country = $api1["countryCode"];
 +
 +// The Log Entry
 +    $logEntry = "<tr><td>$date</td><td>$time</td><td>$publicIp</td><td><a href='https://www.whois.com/whois/$hostName' target='blank'>
 +    $hostName</a></td><td>$userBrowser</td><td>$platform</td><td>$isp</td><td>$timezone</td><td>$country</td></tr>";
 +    
 +// Create Viewer or Create Entry in Log File
 +    if (!file_exists(STATS_FILE)) {
 +        $htmlWrite = fopen(STATS_FILE,"w");
 +        fwrite($htmlWrite, $statsHtml);
 +    }
 +    else {
 +           file_put_contents((LOG_FILE),$logEntry."\n".rtrim(file_get_contents(LOG_FILE)));
 +    }
 +
 +// Trim logfile to max lines - 2 lines per record
 +       $logEntries = file(LOG_FILE);
 +       $lines = count($logEntries);
 +     if ($lines > (MAX_RECORDS) *2) {
 +        array_pop($logEntries);
 +        array_pop($logEntries);      
 +        file_put_contents((LOG_FILE), $logEntries);
 +        }
 +?>
 +</code>
 +
 +
 +The best lightweight self hosted PHP web stats logger in my opinion is ((https://www.bbclone.de))
 +
  
web_stats.1714586237.txt.gz · Last modified: 2024/05/01 17:57 by admin