BigToach.com

PHP Snippets

stats

Information

(PHP Version >= 4.3.0)
Functions used in this snippet: file_exists, file_get_contents, unserialize, date, isset, str_replace, time, is_array, unset, strtotime, count, fopen, fwrite, serialize, fclose.

Description

array stats( str file)

Returns an array holding the values of hits today, hits yesterday, users currently online and total number of hits. The function stores the data in the file file.
On failure the functions returns false

Snippet

<?php
function stats($file,$interval=1){
    if(
file_exists($file)){
        
$str file_get_contents($file);
        
$array unserialize($str);
        
$array is_array($array) ? $array : array();
        
$array['dayhits'][date('dmy')] = isset($array['dayhits'][date('dmy')]) ? $array['dayhits'][date('dmy')]+1;
        
$array['online'][str_replace('.''_'$_SERVER['REMOTE_ADDR'])] = time();
        
$array['alltime'] = isset($array['alltime']) ? $array['alltime']+1;
        if(
is_array($array['online'])){
            foreach(
$array['online'] as $ip=>$time){
                if(
$time < (time() - ($interval 60))){
                    unset(
$array['online'][$ip]);
                }
            }
        }else{
            
$array['online'] = array();
        }
        
$ret['hits'] = $array['alltime'];
        
$ret['today'] = $array['dayhits'][date('dmy')];
        
$yesterday date('dmy'strtotime('-1 day'));
        
$ret['yesterday'] = isset($array['dayhits'][$yesterday]) ? $array['dayhits'][$yesterday] : 0;
        
$ret['online'] = count($array['online']);
        
$fp fopen($file'w');
        
fwrite($fpserialize($array));
        
fclose($fp);
        
print_r($array);
        return 
$ret;
    }
    return 
false;
}
?>

Example

stats Can be used in the following way:

<?php
$stats 
stats('stats.txt');
echo 
'There have been ' $stats['today'] . ' hits today. There were ' $stats['yesterday'] . ' hits yesterday. There are a total of ' $stats['hits'] . ' hits and there is currently ' $stats['online'] . ' users on this page.';
?>

Added on Jun 27th at 7 am by Scott - 0 Comments
Updated on Jun 27th at 7 am.


0 Responses to stats

Name:

Site or Mail:

Comment:

To try to reduce the ammount of spam, please enter the word GOOSE in the following form

Security Code: