doogal.co.uk Home

PHP Hit Stats



Here's some code I wrote a long time ago to log to a text file what files are being accessed on my website. But in this day and age, Google Analytics does a much better job.

Writing To The File

First up, here's the code to write to the file. This function is called on each of my pages

<?
  
function WriteBrowserInfo($FileName)
  {
        
$File fopen("hit_info.txt""a");
    
        if(
$File)
        {
            
$FileName substr($FileNamestrrpos($FileName'/')+1);
            
$ReadDate date("d/m/y H:i:s");
            
fputs($File$ReadDate " " $FileName " " $_SERVER['REMOTE_ADDR'] . " " $_SERVER['HTTP_REFERER'] . "\n");
            
fclose($File);
        }    
  }
?>

Hits Per Day

Next, here's the code to analyse the data. This shows how many hits I'm getting per day

<?
    
function OutputTableRow($Day$Hits)
    {
        
// start table
        
print("<table border=\"0\">\n");    
        print(
"<tr>\n");
    print(
"<td width=\"80\">" $Day "</td>\n");
    print(
"<td width=\"30\">" $Hits "</td>\n");
        print(
"<td width=\"" $Hits "\" bgcolor=\"#FF0000\"></td>\n");
      print(
"</tr>\n");
        
// end table
        
print("</table>\n");
    }
    
    function 
HitsPerDay()
    {
    
$Stats file("hit_info.txt");
    
$Count 1;
            
    for(
$Loop 0$Loop count($Stats)-1$Loop++)
    {
        
$ThisLine explode(' '$Stats[$Loop]);
        
$NextLine explode(' '$Stats[$Loop+1]);
            
        if(
strcmp($ThisLine[0], $NextLine[0]) == 0)
        {
            
$Count++;
        }
        else
        {    
            
OutputTableRow($ThisLine[0], $Count);
            
$Count 1;
        }
    }
      
OutputTableRow($NextLine[0], $Count);
    }
?>

Hits Per Page

Finally, here's some code to work out which pages are getting hits

<?
    
function OutputPageRow($Page$Hits)
    {
        
// start table
        
print("<table border=\"0\">\n");    
        print(
"<tr>\n");
    print(
"<td width=\"150\">" $Page "</td>\n");
    print(
"<td width=\"30\">" $Hits "</td>\n");
        print(
"<td width=\"" $Hits "\" bgcolor=\"#FF0000\"></td>\n");
      print(
"</tr>\n");
        
// end table
        
print("</table>\n");
    }
    
    function 
HitsPerPage()
    {
        
$Stats file("hit_info.txt");
      
$Pages = array(); 
    
      for(
$Loop 0$Loop count($Stats); $Loop++) 
      {  
        
$Page explode(' '$Stats[$Loop]);
            
array_push($Pages$Page[2]);
        }
    
        
sort($Pages);
        
        
$Count=1;
        for(
$Loop 0$Loop count($Pages)-1$Loop++) 
        { 
            if(
strcmp($Pages[$Loop], $Pages[$Loop+1]) == 0
            { 
                
$Count++; 
            } 
            else 
            { 
                
OutputPageRow($Pages[$Loop], $Count); 
                
$Count 1
            } 
        } 
        
OutputPageRow($Pages[$Loop], $Count);
    }
?>