WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
PHP Web Logs (BLogs)
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Submit Site
Forex Trading Online forex trading platform

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : logger class (PHP5 +)
Categories : PHP, PHP Classes, Log Files, XML Click here to Update Your Picture
Johan Barbier
Date : Apr 20th 2006
Grade : 1 of 5 (graded 2 times)
Viewed : 6188
File : 4384.zip
Images : No Images for this code example.
Search : More code by Johan Barbier
Action : Grade This Code Example
Tools : My Examples List

  Submit your own code examples 
 

This is a log class.The class in itself is in the folder 'class/class.oLogger.php'

The 2 files log.consult.php and log.detail.php are here to show an exemple of how to handle these logs. I took them from my own UI, so...I just did what needed to be done for them to work locally.
You can (and should) modify them for your use! But I think that this is a good start.

The logs are already created, of course, But, to create them, here is what I did :

I put this code in my database class oDB, in its query method (like mysql_query...).
I do not log the SELECT queries, but that's a choice. So, my code is just this one :

<?php
if (true === $log && substr (strtoupper (trim ($this->s_db_sql)), 0, 6) !== 'SELECT') {
   
$ologger = new oLogger;
   
$destId = (isset ($_SESSION['dest_id']))?$_SESSION['dest_id']:0;
   
$ologger -> init ($this -> s_db_sql, $destId);
}
?>


That's all! It's enough to create the needed logs through the whole application.
Oh : $_SESSION['dest_id'] contains the current user id. Just replace it by YOUR way to store your user's id.

<?php
/**
* class oLogger
* @author : johan <barbier_johan@hotmail.com>
* @version : 2006-04-20
*/
class oLogger {

   
/**
    * const sLogDir
    * path to the logs
    */
   
const sLogDir ='logs';

   
/**
    * private array aLogs
    * array to store each log line
    */
   
private $aLogs = array (
           
'PAGE' => '',
           
'DATE' => '',
           
'QUERY' => '',
           
'TYPE' => ''
           
);

   
/**
    * private array aLevels
    * array to store the query types
    */
   
private $aLevels = array (
       
0 => 'UNKNOWN',
       
1 => 'SELECT',
       
2 => 'UPDATE',
       
3 => 'INSERT',
       
4 => 'DELETE'
       
);

   
/**
    * public array aDir
    * array to store all the log folders and log files
    */
   
public $aDir = array ();

   
/**
    * private object oXml
    * a simple_xml object
    */
   
private $oXml = null;

   
/**
    * public function __construct
    * the constructor
    * initailizes the simple_xml object if needed
    * @param (string) file : the xml log file from which will be set the simple_xml object property
    */
   
public function __construct ($file = '') {
        if (!empty (
$file)) {
           
$this -> oXml = simplexml_load_file(self::sLogDir.'/'.$file);
        }
    }

   
/**
    * public function init
    * initializes the logger
    * gets the sql query, the user id, current date, filename, query type, and builds the aLogs array with all of that
    * @param (string) sSql : the sql query we want to log
    * @param (int) destId : the user id (depends on your system)
    */
   
public function init ($sSql, $destId) {
       
$page = $_SERVER['PHP_SELF'];
       
$this -> checkDir ($destId);
       
$date = date ('H:i:s');
       
$file = date ('Ymd').'.xml';
       
$sSql = trim (preg_replace ('@(\s)+@', ' ', $sSql));
       
$aSql = explode (' ', $sSql);
        if (
false === ($level = array_search ($aSql[0], $this -> aLevels))) {
           
$level = 0;
        }
       
$this -> aLogs = array (
           
'PAGE' => $page,
           
'DATE' => $date,
           
'QUERY' => $sSql,
           
'TYPE' => $this -> aLevels[$level]
            );
       
$this -> logIt ($file, $destId);
    }

   
/**
    * private function checkDir
    * used to check if a log folder exists for a given user id. If not, creates it.
    * @param (int) id : the user id
    */
   
private function checkDir ($id) {
        if (!
file_exists (self::sLogDir.'/'.$id)) {
           
mkdir (self::sLogDir.'/'.$id);
        }
    }

   
/**
    * private function logIt
    * build the xml from the aLogs array, and saves it into the given file
    * if the given file already exists, it appends the new xml to the existing one
    * @param (string) file : the filename in which the xml log will be written
    * @param (int) destId : the user id (depends on your system)
    */
   
private function logIt ($file, $destId) {
        if (
file_exists (self::sLogDir.'/'.$destId.'/'.$file)) {
           
$docXml = DOMDocument::load (self::sLogDir.'/'.$destId.'/'.$file);
           
$root = $docXml -> documentElement;
        } else {
           
$docXml = new DOMDocument('1.0', 'iso-8859-1');
           
$root = $docXml -> createElement ('logs');
           
$root = $docXml -> appendChild ($root);
        }
       
$log = $docXml -> createElement ('log');
       
$log = $root -> appendChild ($log);
        foreach (
$this -> aLogs as $clef => $val) {
           
$xmlClef = $docXml -> createElement ($clef);
           
$xmlClef = $log -> appendChild ($xmlClef);
           
$xmlVal = $docXml -> createTextNode ($val);
           
$xmlVal = $xmlClef -> appendChild ($xmlVal);
        }
       
$docXml -> save (self::sLogDir.'/'.$destId.'/'.$file);
       
$this -> aLogs = array ();
    }

   
/**
    * public function getaDir
    * builds the aDir array, in which are stored all the log folders and log files
    * @param (bool) ordID : if set to true, orders the array by users id ASC
    */
   
public function getaDir ($ordID = false) {
       
$aDestLogs = scandir (self::sLogDir);
       
$aDestLogs = array_splice ($aDestLogs, 2);
        if (
true === $ordID) {
           
sort ($aDestLogs, SORT_NUMERIC);
        }
        if (!empty (
$aDestLogs)) {
            foreach (
$aDestLogs as $v) {
               
$aFiles = scandir (self::sLogDir.'/'.$v);
               
$aFiles = array_splice ($aFiles, 2);
               
$this -> aDir[$v] = $aFiles;
            }
        } else {
           
$this -> aDir = array ();
        }
    }

   
/**
    * public function getList
    * builds an array from the oXml simple_xml object with all the values it contains in the $type xml element (the available types are the aLogs array keys)
    * used for the logs UI : with this method, I can display only the UPDATE, or the INSERT, or only a given page on the logged website...
    * @param (string) type : the type on wihch we want to filter. Must be a valid aLogs key.
    */
   
public function getList ($type) {
        if (!
array_key_exists ($type, $this -> aLogs)) {
           
trigger_error ('Type '.$type.' non reconnu', E_USER_ERROR);
        }
       
$oTypes = $this -> oXml -> xpath ('log/'.$type);
       
$aType = array_unique ($oTypes);
        return
$aType;
    }

   
/**
    * public function getDetail
    * transforms the xml in a log file to html. Could unfortunately not use the XSLTProcessor, because my server did not implement it :-(
    * the html can, be changed, of course. The javascript is a javascript function used to get a filter, if needed.
    * @param (bool) ord : if set to true, we reverse the xml; as the xml is logged chronologically, we will reverse the dates.
    * @param (string) type : if not empty, we filter on that type.
    * @param (string) page : if not empty, we filter on that page.
    */
   
public function getDetail ($ord = false, $type = '', $page = '') {
       
$sXml = '';
       
$oLignes = $this -> oXml -> xpath ('log');
        if (
true === $ord) {
           
$oLignes = array_reverse ($oLignes);
        }
       
$iCpt = 0;
        foreach (
$oLignes as $log) {
            if (!empty (
$type) && $log -> TYPE != $type) {
                continue;
            }
            if (!empty (
$page) && $log -> PAGE != $page) {
                continue;
            }
           
$sColor = ($iCpt%2) ? 'ct1' : 'ct2';
           
$sXml .= <<<HTML
            <tr>
                <td class="$sColor">
{$log -> DATE}</td>
                <td class="$sColor"><a href="javascript:filtrePage('
{$log -> PAGE}');">{$log -> PAGE}</a></td>
                <td class="$sColor"><a href="javascript:filtreType('
{$log -> TYPE}');">{$log -> TYPE}</a></td>
                <td class="$sColor">
{$log -> QUERY}</td>
            </tr>
HTML;
       
$iCpt ++;
        }
        return
$sXml;
    }
}
?>



RSS parser. Parses RSS into an array. Quick and nasty but does the job. No checking is done for correct Tags, only correct XML. PHP4 needed to display result (uses print_r).
Categories : PHP, XML, PHP Classes, Rich Site Summary (RSS)
XML To Array
Categories : PHP, PHP Classes, XML, Arrays
A very basic and fast XML parser
Categories : PHP, PHP Classes, XML
PHP Based Apache + Mysql Error Log Parser
Categories : PHP, PHP Classes, Apache, MySQL, Log Files
An efficient iterative and buffered text file reader
Categories : PHP, Classes and Objects, Filesystem, PHP Classes, Log Files
XML Menu
Categories : PHP, PHP Classes, Navigation, XML, XSL
Directory Listing To XML : Outputs XML File of a Given Directory Listing
Categories : PHP, PHP Classes, XML, Directories
Freshmeat.net XML-RPC - This class is meant to query Freshmeat for information about registered projects.
Categories : PHP, PHP Classes, XML, Web Services
DBXML- A Class to backup databases in XML Format using web interface
Categories : PHP, PHP Classes, Databases, MySQL, XML
TAB_STRUCT Class: Is supporting Class for the DBXML Class
Categories : PHP, PHP Classes, MySQL, XML, Databases
XML easy parser
Categories : PHP, XML, PHP Classes
filesplit : Split big text files in multiple small ones
Categories : PHP, Log Files, Filesystem, PHP Classes
Scan Apache access log files and report possible worms attack
Categories : PHP, PHP Classes, Security, Apache, Log Files
[PHP5] PHP Debugger and Helper
Categories : PHP, PHP Classes, Errors and Logging, Debugging, XML
XPath for PHP without the DOM XML extension
Categories : DOM XML, XML, XSLT, PHP Classes, PHP