In this tutorial, we will explore the creation of an activity log feature in web applications using the PHP language. The objective is to offer students and those new to the PHP language a reference or guide to enhance their knowledge and capabilities in developing efficient and effective web applications. I will explain the step-by-step process of creating a reusable PHP Class that implements an Activity Log feature into a PHP project. Additionally, I will provide a complete source code zip file for a sample web application that demonstrates the usage of the mentioned PHP Class.
Implementing an Activity Log in web applications provides tailored advantages for the dynamic nature of online platforms. Careful consideration of the information to be logged is crucial, balancing the need for detailed records with concerns for data privacy and performance. When implemented effectively, an activity log can significantly contribute to the security, performance, and usability of web applications.
Here are the steps for creating an Activity Logger Class in PHP:
Assuming that we have already created a new PHP file named `activity-log.class.php
`, open the file in your preferred code editor, such as Sublime Text, MS VS Code, or Notepad++. Then, structure the PHP class as follows:
<?php class ActivityLog{ } ?>
Next, we need to create the class method or function that allows us to connect to the Database. We can achieve this by adding the database connection in the `__construct
` function of the class and closing it in the `__destruct
` function. To do this, refer to the following snippet:
<?php class ActivityLog{ // DB Connection object private $db; function __construct($dbhost="", $dbuser = "", $dbpassword = "", $dbname = "", $db_prefix =""){ // Check if DB credentials is empty throw new ErrorException("Database Credentials cannot be empty!"); exit; } // Connect to the database try{ $this->db = new MySQLi($dbhost, $dbuser, $dbpassword, $dbname); }catch(Exception $e){ throw new ErrorException($e->getMessage()); exit; } } function __destruct() { if($this->db){ $this->db->close(); } } } ?>
Next, let's create the function that checks if the Activity Log's Table is already created; otherwise, the function will create a new database table for this. See the following snippet:
<?php class ActivityLog{ // DB Connection private $db; // Log Table Name private $dbTbl = "site_activity_log_automation_tbl"; // DB Prefix private $db_prefix; function __construct($dbhost="", $dbuser = "", $dbpassword = "", $dbname = "", $db_prefix =""){ // Check if DB credentials is empty throw new ErrorException("Database Credentials cannot be empty!"); exit; } // Connect to the database try{ $this->db = new MySQLi($dbhost, $dbuser, $dbpassword, $dbname); }catch(Exception $e){ throw new ErrorException($e->getMessage()); exit; } // SEt DB Prefix to log db table $this->db_prefix = $db_prefix; $this->db_prefix .= "_"; } $this->dbTbl = $this->db_prefix . $this->dbTbl; // Check if Log Table already exists, otherwise, create table try{ $tbl_described = $this->db->query("DESCRIBE `{$this->db_prefix}`"); }catch(Exception $e){ $this->create_tbl(); } } /** * Log Table Creation */ function create_tbl(){ $sql = "CREATE TABLE IF NOT EXISTS `{$this->dbTbl}` ( `id` bigint(30) PRIMARY KEY AUTO_INCREMENT, `user_id` bigint(30) NOT NULL, `ip` varchar(25) NOT NULL, `url` text NOT NULL, `action` text NOT NULL, `created_at` datetime NOT NULL DEFAULT current_timestamp() )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci "; try{ $table_create = $this->db->query($sql); }catch(Exception $e){ throw new ErrorException($e->getMessage()); exit; } } function __destruct() { if($this->db){ $this->db->close(); } } } ?>
The snippet above showcases the creation of the Activity Log Table if the table does not exist yet and when the class is called.
Next, let's create the function that inserts the log data into the database. To do that, we can write it as follows:
<?php /** * Sanitize values * @param mixed any */ function sanitize_value($value){ }else{ } } return $value; } /** * Insert Activity Log * @param array [user_id, ip, url, action] * */ throw new ErrorException("Log data are required!"); exit; } $params_values = []; $params_format = []; $query_values = []; foreach($data as $k => $v){ $v = $this->sanitize_value($v); $fmt = "d"; }else{ $fmt = "s"; } $query_values[] = "`{$k}`"; $params_values[] = $v; $params_format[] = $fmt; } } throw new ErrorException("All Log data provided are empty or invalid!"); exit; } $sql = "INSERT INTO `{$this->dbTbl}` (".implode(",", $query_values).") VALUES (".( implode( ",", str_split( str_repeat( "?", count( $query_values ) ) ) ) ).")"; $stmt = $this->db->prepare($sql); $stmt->bind_param($fmts, ...$params_values); $executed = $stmt->execute(); if($executed){ $resp = [ "status" => "success" ]; }else{ $resp = [ "status" => "error", "sql" => $sql, "queries" => $query_values, "formats" => $fmts, "values" => $params_values, ]; } return $resp; } ?>
Here's the complete script of the reusable Activity Log class in PHP. I've also included a function that retrieves all the activity logs from the database.
<?php /** * Class Required Parameters * @param str DB Host Name * @param str DB User Name * @param str DB Password * @param str DB Name * @param str DB Prefix */ class ActivityLog{ // DB Connection private $db; // Log Table Name private $dbTbl = "site_activity_log_automation_tbl"; // DB Prefix private $db_prefix; function __construct($dbhost="", $dbuser = "", $dbpassword = "", $dbname = "", $db_prefix =""){ // Check if DB credentials is empty throw new ErrorException("Database Credentials cannot be empty!"); exit; } // Connect to the database try{ $this->db = new MySQLi($dbhost, $dbuser, $dbpassword, $dbname); }catch(Exception $e){ throw new ErrorException($e->getMessage()); exit; } // SEt DB Prefix to log db table $this->db_prefix = $db_prefix; $this->db_prefix .= "_"; } $this->dbTbl = $this->db_prefix . $this->dbTbl; // Check if Log Table already exists, otherwise, create table try{ $tbl_described = $this->db->query("DESCRIBE `{$this->db_prefix}`"); }catch(Exception $e){ $this->create_tbl(); } } /** * Log Table Creation */ function create_tbl(){ $sql = "CREATE TABLE IF NOT EXISTS `{$this->dbTbl}` ( `id` bigint(30) PRIMARY KEY AUTO_INCREMENT, `user_id` bigint(30) NOT NULL, `ip` varchar(25) NOT NULL, `url` text NOT NULL, `action` text NOT NULL, `created_at` datetime NOT NULL DEFAULT current_timestamp() )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci "; try{ $table_create = $this->db->query($sql); }catch(Exception $e){ throw new ErrorException($e->getMessage()); exit; } } /** * Sanitize values * @param mixed any */ function sanitize_value($value){ }else{ } } return $value; } /** * Insert Activity Log * @param array [user_id, ip, url, action] * */ throw new ErrorException("Log data are required!"); exit; } $params_values = []; $params_format = []; $query_values = []; foreach($data as $k => $v){ $v = $this->sanitize_value($v); $fmt = "d"; }else{ $fmt = "s"; } $query_values[] = "`{$k}`"; $params_values[] = $v; $params_format[] = $fmt; } } throw new ErrorException("All Log data provided are empty or invalid!"); exit; } $sql = "INSERT INTO `{$this->dbTbl}` (".implode(",", $query_values).") VALUES (".( implode( ",", str_split( str_repeat( "?", count( $query_values ) ) ) ) ).")"; $stmt = $this->db->prepare($sql); $stmt->bind_param($fmts, ...$params_values); $executed = $stmt->execute(); if($executed){ $resp = [ "status" => "success" ]; }else{ $resp = [ "status" => "error", "sql" => $sql, "queries" => $query_values, "formats" => $fmts, "values" => $params_values, ]; } return $resp; } /** * Log Data * @param $user_id mixed|int User ID * @param $action str Action Data */ public function setAction($user_id= "", $action = ""){ $data = []; $data['ip'] = $REMOTE_ADDR; $data["user_id"] = $user_id; } /** * Get All Logs */ public function getLogs(){ $query = $this->db->query("SELECT * FROM `{$this->dbTbl}` order by `id` desc"); $result = $query->fetch_all(MYSQLI_ASSOC); return $result; } function __destruct() { if($this->db){ $this->db->close(); } } } ?>
Using the PHP Class provided above, we can now log the actions or any activity of the users in the website by simply implementing the script like the following:
<?php $dbData = [ "localhost", // Hostname "root", // Username "", // Password "dummy_db" // DBName ]; $activityLog = new ActivityLog(...$dbData); $activityLog->setAction($_SESSION['user_id'], "accessed the home page"); ?>
To gain a better understanding of the usage of the PHP Activity Logger Class provided above, I've developed a simple web application with CRUD (Create, Read, Update, and Delete) functionalities. In this web application, user activities are logged in the database, such as successful logins, adding new data, updating data, and deleting data. The complete source code zip file of the web application I created is available and is free to download on this website. The download button is located below this tutorial content.
Explore the snapshots below, showcasing the Sample Web Application I created:
And there you have it! I trust this Creation Activity Logger PHP Class Tutorial will be beneficial for your needs and prove valuable for your current and future PHP projects. Delve deeper into this website for additional Tutorials, Free Source Codes, and Articles covering various programming languages.
You may also find interest in exploring the following: