MaggsWeb:7

www.maggsweb.com

Logging user activity

August 22, 2007 | Comments | PHP

Logging user activity is vital when there are multiple authors for a site. It also helps with debugging user activity when there is problems. You certainly don’t want to be putting this into a database, so the next best thing is a nice little text file.
I have used this to log user activity in a number of sites, as it can easily be added after development. In this example, $PAGE and $pageTitle are set in each page as they are used to determine menu selections, etc.. but these can easily be set manually.

<?php
function add2log($var1,$var2,$var3) {
    global $PAGE;
    global $PageTitle;
    # create array
    $logArray = array();
    $logArray[] = $_SESSION['loginname'];
    $logArray[] = $_SESSION['accesslevel'];
    $logArray[] = $_SERVER['REMOTE_ADDR'];
    $logArray[] = date("Y-m-d H:i:s",time()-3600);
    $logArray[] = $PAGE;
    $logArray[] = $PageTitle;
    $logArray[] = $var1;
    $logArray[] = $var2;
    $logArray[] = $var3;
    # create csv from array
    $logDetails = "\n".implode(",",$logArray);
    # sort dir
    $dir = $_SERVER['DOCUMENT_ROOT']."/../_logs/";
    //if (!is_dir($dir)) mkdir($dir,0777);
    #make filename
    $file = $dir.date("Y-m-d", (time()-3600)).".htm";
    #write to file
    if (!$file_handle = fopen($file,"a")) 	$ERROR; exit;
    if (!fwrite($file_handle, $logDetails)) 	$ERROR; exit;
    fclose($file_handle);
}
?>

This creates nice little log files for each day, that can be displayed, exported, imported, searched, etc…

Share this:
  • Print
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • LinkedIn
  • Twitter

Write a Comment

Let me know what you think?