CodeIgniter log library Code. PHP-Framework

<?php

defined('BASEPATH') OR exit('No direct script access allowed');
class Event_logger {
  /**
     * ci
     *
     * @param instance object
     */
 protected $CI;
    /**
     * log table name
     *
     * @param string
     */
    private $_log_table_name = 'event_logs';

 // We'll use a constructor, as you can't directly call a function
 // from a property definition.
 
 public function __construct()
 {
   // Assign the CodeIgniter super-object
   $this->CI =& get_instance();
      $this->CI->load->database();
   $this->_log_table_name = 'event_logs';
 }
 
 /*
  Logger Function
 */
 public function log_event($event,$data,$table,$unique_identifier="",$unique_identifier_value=''){
  if(!$this->CI->db->table_exists($table) )
  {
   echo "Event Logger : Table - $table  does not exists";
   exit();
  }
  
  if($event == "update")
  {
   if(empty($unique_identifier) || empty($unique_identifier_value))
   {
    echo "Event Logger : Update operation unique key not defined";
    exit();
   }
   
   $logData = "";
   
   if(!empty($data) > 0 ){
    foreach($data as $key=>$value){
     $sql = "SELECT $key FROM $table WHERE $unique_identifier = $unique_identifier_value";
     $query = $this->CI->db->query($sql);
     $row = $query->row();
     if (isset($row)){
      if(strtolower($row->$key) != strtolower($value)){
       $logData[$key] = array("old_value"=>$row->$key,"new_value" => $value);
      }
     } 
    }
    
    if(!empty($logData)){
      $finalData = array(
           'event_name' =>$event,
           'event_table' =>$table,
           'table_unique_id' =>$unique_identifier,
           'unique_id' =>$unique_identifier_value,
           'event_values' =>json_encode($logData),
           'updated_by' => $this->CI->session->userdata('admin_id'),
           'ip_address' => $this->CI->input->ip_address(),
           'user_agent' => $this->CI->input->user_agent(),
           'added_on' => date('Y-m-d H:i:s'),
    
         );
     $this->CI->db->insert($this->_log_table_name, $finalData);
    }
   }else{
    echo "Event Logger : update event data is blank";
    exit();
   }
  }
  
  
  if($event == "insert"){
   
   $finalData = array(
           'event_name' => $event,
           'event_table' =>$table,
           'event_values' =>json_encode($data),
           'updated_by' => $this->CI->session->userdata('admin_id'),
           'ip_address' => $this->CI->input->ip_address(),
           'user_agent' => $this->CI->input->user_agent(),
           'added_on' => date('Y-m-d H:i:s'),
    
         );
   $this->CI->db->insert($this->_log_table_name, $finalData);
  }
  
  if($event == "delete"){
   
   $sql = "SELECT * FROM $table WHERE $unique_identifier = $unique_identifier_value";
   $query = $this->CI->db->query($sql);
   $row = $query->row();
   $finalData = array(
           'event_name' => $event,
           'event_table' =>$table,
           'event_values' =>json_encode($row),
           'updated_by' => $this->CI->session->userdata('admin_id'),
           'ip_address' => $this->CI->input->ip_address(),
           'user_agent' => $this->CI->input->user_agent(),
           'added_on' => date('Y-m-d H:i:s'),
    
         );
   $this->CI->db->insert($this->_log_table_name, $finalData);
  }
    
 }
 
}

defined('BASEPATH') OR exit('No direct script access allowed');

This line checks if the constant BASEPATH is defined. This is a security measure in CodeIgniter to prevent direct access to the script. If someone tries to access this file directly via a URL, the script will exit, ensuring that it can only be accessed through the framework.

Class Definition

class Event_logger {

This line defines a new class named Event_logger. This class is responsible for logging events (like insert, update, and delete operations) in a database table.

Properties

protected $CI;
private $_log_table_name = 'event_logs';
  • $CI: This property holds a reference to the CodeIgniter super-object, which gives access to all the libraries and helpers loaded in the application.
  • $_log_table_name: This private property stores the name of the database table where event logs will be saved, which is set to 'event_logs'.

Constructor

public function __construct()
{
    $this->CI =& get_instance();
    $this->CI->load->database();
    $this->_log_table_name = 'event_logs';
}

The constructor is called when an instance of the class is created. Here:

  • get_instance() retrieves the CodeIgniter super-object and assigns it to $CI.
  • The database library is loaded, allowing the class to interact with the database.
  • The log table name is initialized (though it’s already set as a default value).

Logging Function

public function log_event($event, $data, $table, $unique_identifier = "", $unique_identifier_value = '')

This method is the core of the class, responsible for logging different types of events. It takes several parameters:

  • $event: The type of event (insert, update, delete).
  • $data: The data associated with the event.
  • $table: The name of the table where the event occurred.
  • $unique_identifier: A unique key for identifying records (used in updates and deletes).
  • $unique_identifier_value: The value of the unique identifier.

Event Handling

The method handles three types of events: update, insert, and delete.

Update Event

if($event == "update")
{
    // Check for unique identifier
    if(empty($unique_identifier) || empty($unique_identifier_value))
    {
        echo "Event Logger : Update operation unique key not defined";
        exit();
    }
    // Log changes
    foreach($data as $key => $value) {
        // Query to get the current value
        $sql = "SELECT $key FROM $table WHERE $unique_identifier = $unique_identifier_value";
        $query = $this->CI->db->query($sql);
        $row = $query->row();
        // Compare old and new values
        if (isset($row) && strtolower($row->$key) != strtolower($value)) {
            $logData[$key] = array("old_value" => $row->$key, "new_value" => $value);
        }
    }
    // Insert log if changes exist
    if (!empty($logData)) {
        $finalData = array(
            'event_name' => $event,
            'event_table' => $table,
            'table_unique_id' => $unique_identifier,
            'unique_id' => $unique_identifier_value,
            'event_values' => json_encode($logData),
            'updated_by' => $this->CI->session->userdata('admin_id'),
            'ip_address' => $this->CI->input->ip_address(),
            'user_agent' => $this->CI->input->user_agent(),
            'added_on' => date('Y-m-d H:i:s'),
        );
        $this->CI->db->insert($this->_log_table_name, $finalData);
    }
}
  • It first checks if the unique identifier is provided. If not, it exits with an error message.
  • It then loops through the $data array to compare old and new values for each field.
  • If changes are detected, it prepares a log entry and inserts it into the event_logs table.

Insert Event

if($event == "insert") {
    $finalData = array(
        'event_name' => $event,
        'event_table' => $table,
        'event_values' => json_encode($data),
        'updated_by' => $this->CI->session->userdata('admin_id'),
        'ip_address' => $this->CI->input->ip_address(),
        'user_agent' => $this->CI->input->user_agent(),
        'added_on' => date('Y-m-d H:i:s'),
    );
    $this->CI->db->insert($this->_log_table_name, $finalData);
}
  • For insert events, it directly logs the new data into the event_logs table without needing to compare values.

Delete Event

if($event == "delete") {
    $sql = "SELECT * FROM $table WHERE $unique_identifier = $unique_identifier_value";
    $query = $this->CI->db->query($sql);
    $row = $query->row();
    $finalData = array(
        'event_name' => $event,
        'event_table' => $table,
        'event_values' => json_encode($row),
        'updated_by' => $this->CI->session->userdata('admin_id'),
        'ip_address' => $this->CI->input->ip_address(),
        'user_agent' => $this->CI->input->user_agent(),
        'added_on' => date('Y-m-d H:i:s'),
    );
    $this->CI->db->insert($this->_log_table_name, $finalData);
}
  • For delete events, it retrieves the record being deleted and logs its details before the deletion occurs.
Techinfo Avatar

Leave a Reply

Your email address will not be published. Required fields are marked *