Total page hits/unique visits snippet

Filed under:  Google about "Drupal" |  Google about "PHP"

I just thought it would be nice to share how do I display the total page hits and unique visits counter on this site's footer.

The following is a small code snippet that you can place wherever you wish, for instance on a block or a PHP template. Of course, you can change the message or customize the look to suit your needs. :-)

<?php
/**
 * Compute the counters.
 */
if (!($counter_since variable_get('mycounter_since'0))) {
  
$page_hits 1;
  
$unique_visits 1;
  
$counter_since time();
  
$_SESSION['mycounter'] = TRUE;
  
variable_set('mycounter_page_hits'1);
  
variable_set('mycounter_unique_visits'1);
  
variable_set('mycounter_since'$counter_since);
}
else {
  
$page_hits = (int)variable_get('mycounter_page_hits'0);
  
$unique_visits = (int)variable_get('mycounter_unique_visits'0);
  if (!isset(
$_SESSION['mycounter'])) {
    
$_SESSION['mycounter'] = TRUE;
    
$unique_visits++;
    
variable_set('mycounter_unique_visits'$unique_visits);
  }
  
$page_hits++;
  
variable_set('mycounter_page_hits'$page_hits);
}

/**
 * Format and display the counters.
 */
print t('Total page hits: %page-hits, unique visits: %unique-visits, since %counter-since', array(
  
'%page-hits' => number_format($page_hits0'.'','),
  
'%unique-visits' => number_format($unique_visits0'.'','),
  
'%counter-since' => format_date($counter_since'custom''F j, Y')
));
?>

It uses the Drupal functions variable_get and variable_set to store the data. There's no admin interface to manage these variables. If you want to modify or remove them, you need to edit the drupal variables table.

Functions used to format the counter: (PHP) number_format and (Drupal) t and format_date.

That's it. I hope it helps someone out there. ;-)


variable_get missing argument 2 error

Thanks for this tidbit of code!

One thing to note: this will give errors on the variable_get lines as variable_get() requires two parameters. Change this"variable_get('mycounter_since')" to "variable_get('mycounter_since', 0)", and change the other two lines:

$page_hits = (int)variable_get('mycounter_page_hits', 1);
$unique_visits = (int)variable_get('mycounter_unique_visits', 1);

That should do it...


Good catch!

It should be fixed above. Thanks :-)


I dunno much about php but

I dunno much about php but when I reload my site this condicional is alway executed (unique visisits is incremented when i reload), so it is not "unique" visits:

if (!isset($_SESSION['mycounter'])) {
$_SESSION['mycounter'] = TRUE;
$unique_visits++;
variable_set('mycounter_unique_visits', $unique_visits);
}

What can I do?


UHm, I think I fixed it by

UHm, I think I fixed it by adding

$_SESSION['mycounter'] = TRUE;

After

variable_set('mycounter_page_hits', $page_hits);