Implementing an Activity Log in Your Web App Using PHP

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.

What are the benefits of implementing an Activity Log in Web Applications?

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.

How to create a reusable Activity Logger Class in PHP?

Here are the steps for creating an Activity Logger Class in PHP:

Step 1: Creating the Class

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:

  1. <?php
  2. class ActivityLog{
  3.  
  4. }
  5. ?>

Step 2: Create a Database Connection

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:

  1. <?php
  2. class ActivityLog{
  3. // DB Connection object
  4. private $db;
  5. function __construct($dbhost="", $dbuser = "", $dbpassword = "", $dbname = "", $db_prefix =""){
  6. // Check if DB credentials is empty
  7. if(empty($dbhost) || empty($dbuser) || empty($dbname)){
  8. throw new ErrorException("Database Credentials cannot be empty!");
  9. }
  10.  
  11. // Connect to the database
  12. try{
  13. $this->db = new MySQLi($dbhost, $dbuser, $dbpassword, $dbname);
  14. }catch(Exception $e){
  15. throw new ErrorException($e->getMessage());
  16. }
  17.  
  18. }
  19. function __destruct()
  20. {
  21. if($this->db){
  22. $this->db->close();
  23. }
  24. }
  25. }
  26. ?>

Step 3: Create the Log Table in Database

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:

  1. <?php
  2. class ActivityLog{
  3.  
  4. // DB Connection
  5. private $db;
  6. // Log Table Name
  7. private $dbTbl = "site_activity_log_automation_tbl";
  8. // DB Prefix
  9. private $db_prefix;
  10.  
  11. function __construct($dbhost="", $dbuser = "", $dbpassword = "", $dbname = "", $db_prefix =""){
  12. // Check if DB credentials is empty
  13. if(empty($dbhost) || empty($dbuser) || empty($dbname)){
  14. throw new ErrorException("Database Credentials cannot be empty!");
  15. }
  16. // Connect to the database
  17. try{
  18. $this->db = new MySQLi($dbhost, $dbuser, $dbpassword, $dbname);
  19. }catch(Exception $e){
  20. throw new ErrorException($e->getMessage());
  21. }
  22.  
  23. // SEt DB Prefix to log db table
  24. $this->db_prefix = $db_prefix;
  25. if(!empty($this->db_prefix)){
  26. $this->db_prefix .= "_";
  27. }
  28. $this->dbTbl = $this->db_prefix . $this->dbTbl;
  29.  
  30.  
  31. // Check if Log Table already exists, otherwise, create table
  32. try{
  33. $tbl_described = $this->db->query("DESCRIBE `{$this->db_prefix}`");
  34. }catch(Exception $e){
  35. $this->create_tbl();
  36. }
  37.  
  38. }
  39.  
  40. /**
  41.   * Log Table Creation
  42.   */
  43. function create_tbl(){
  44. $sql = "CREATE TABLE IF NOT EXISTS `{$this->dbTbl}`
  45. (
  46. `id` bigint(30) PRIMARY KEY AUTO_INCREMENT,
  47. `user_id` bigint(30) NOT NULL,
  48. `ip` varchar(25) NOT NULL,
  49. `url` text NOT NULL,
  50. `action` text NOT NULL,
  51. `created_at` datetime NOT NULL DEFAULT current_timestamp()
  52. )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
  53. ";
  54. try{
  55. $table_create = $this->db->query($sql);
  56. }catch(Exception $e){
  57. throw new ErrorException($e->getMessage());
  58. }
  59. }
  60. function __destruct()
  61. {
  62. if($this->db){
  63. $this->db->close();
  64. }
  65. }
  66. }
  67. ?>

The snippet above showcases the creation of the Activity Log Table if the table does not exist yet and when the class is called.

Step 4: Creating a Log Function

Next, let's create the function that inserts the log data into the database. To do that, we can write it as follows:

  1. <?php
  2. /**
  3. * Sanitize values
  4. * @param mixed any
  5. */
  6. function sanitize_value($value){
  7. if(!is_numeric($value) && empty($value)){
  8. if( is_object($value) && is_array($value) ){
  9. $value = json_encode($value);
  10. }else{
  11. $value = addslashes(htmlspecialchars($value));
  12. }
  13. }
  14. return $value;
  15. }
  16.  
  17. /**
  18.   * Insert Activity Log
  19.   * @param array [user_id, ip, url, action]
  20.   *
  21.   */
  22. public function log( $data = [] ){
  23. if(empty($data)){
  24. throw new ErrorException("Log data are required!");
  25. }
  26.  
  27.  
  28. $params_values = [];
  29. $params_format = [];
  30. $query_values = [];
  31.  
  32. foreach($data as $k => $v){
  33. $v = $this->sanitize_value($v);
  34. if(!empty($v)){
  35. if(is_numeric($v)){
  36. $fmt = "d";
  37. }else{
  38. $fmt = "s";
  39. }
  40. $query_values[] = "`{$k}`";
  41. $params_values[] = $v;
  42. $params_format[] = $fmt;
  43. }
  44. }
  45.  
  46. if(empty($query_values)){
  47. throw new ErrorException("All Log data provided are empty or invalid!");
  48. }
  49.  
  50. $sql = "INSERT INTO `{$this->dbTbl}` (".implode(",", $query_values).") VALUES (".( implode( ",", str_split( str_repeat( "?", count( $query_values ) ) ) ) ).")";
  51.  
  52. $stmt = $this->db->prepare($sql);
  53.  
  54. $fmts = implode("", $params_format);
  55.  
  56. $stmt->bind_param($fmts, ...$params_values);
  57.  
  58. $executed = $stmt->execute();
  59.  
  60. if($executed){
  61.  
  62. $resp = [
  63. "status" => "success"
  64. ];
  65.  
  66. }else{
  67.  
  68. $resp = [
  69. "status" => "error",
  70. "sql" => $sql,
  71. "queries" => $query_values,
  72. "formats" => $fmts,
  73. "values" => $params_values,
  74. ];
  75.  
  76. }
  77. return $resp;
  78. }
  79. ?>

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.

  1. <?php
  2. /**
  3.  * Class Required Parameters
  4.  * @param str DB Host Name
  5.  * @param str DB User Name
  6.  * @param str DB Password
  7.  * @param str DB Name
  8.  * @param str DB Prefix
  9. */
  10. class ActivityLog{
  11.  
  12. // DB Connection
  13. private $db;
  14. // Log Table Name
  15. private $dbTbl = "site_activity_log_automation_tbl";
  16. // DB Prefix
  17. private $db_prefix;
  18.  
  19. function __construct($dbhost="", $dbuser = "", $dbpassword = "", $dbname = "", $db_prefix =""){
  20. // Check if DB credentials is empty
  21. if(empty($dbhost) || empty($dbuser) || empty($dbname)){
  22. throw new ErrorException("Database Credentials cannot be empty!");
  23. }
  24. // Connect to the database
  25. try{
  26. $this->db = new MySQLi($dbhost, $dbuser, $dbpassword, $dbname);
  27. }catch(Exception $e){
  28. throw new ErrorException($e->getMessage());
  29. }
  30.  
  31. // SEt DB Prefix to log db table
  32. $this->db_prefix = $db_prefix;
  33. if(!empty($this->db_prefix)){
  34. $this->db_prefix .= "_";
  35. }
  36. $this->dbTbl = $this->db_prefix . $this->dbTbl;
  37.  
  38.  
  39. // Check if Log Table already exists, otherwise, create table
  40. try{
  41. $tbl_described = $this->db->query("DESCRIBE `{$this->db_prefix}`");
  42. }catch(Exception $e){
  43. $this->create_tbl();
  44. }
  45.  
  46. }
  47.  
  48. /**
  49.   * Log Table Creation
  50.   */
  51. function create_tbl(){
  52. $sql = "CREATE TABLE IF NOT EXISTS `{$this->dbTbl}`
  53. (
  54. `id` bigint(30) PRIMARY KEY AUTO_INCREMENT,
  55. `user_id` bigint(30) NOT NULL,
  56. `ip` varchar(25) NOT NULL,
  57. `url` text NOT NULL,
  58. `action` text NOT NULL,
  59. `created_at` datetime NOT NULL DEFAULT current_timestamp()
  60. )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
  61. ";
  62. try{
  63. $table_create = $this->db->query($sql);
  64. }catch(Exception $e){
  65. throw new ErrorException($e->getMessage());
  66. }
  67. }
  68.  
  69. /**
  70.   * Sanitize values
  71.   * @param mixed any
  72.   */
  73. function sanitize_value($value){
  74. if(!is_numeric($value) && empty($value)){
  75. if( is_object($value) && is_array($value) ){
  76. $value = json_encode($value);
  77. }else{
  78. $value = addslashes(htmlspecialchars($value));
  79. }
  80. }
  81. return $value;
  82. }
  83.  
  84. /**
  85.   * Insert Activity Log
  86.   * @param array [user_id, ip, url, action]
  87.   *
  88.   */
  89. public function log( $data = [] ){
  90. if(empty($data)){
  91. throw new ErrorException("Log data are required!");
  92. }
  93.  
  94.  
  95. $params_values = [];
  96. $params_format = [];
  97. $query_values = [];
  98.  
  99. foreach($data as $k => $v){
  100. $v = $this->sanitize_value($v);
  101. if(!empty($v)){
  102. if(is_numeric($v)){
  103. $fmt = "d";
  104. }else{
  105. $fmt = "s";
  106. }
  107. $query_values[] = "`{$k}`";
  108. $params_values[] = $v;
  109. $params_format[] = $fmt;
  110. }
  111. }
  112.  
  113. if(empty($query_values)){
  114. throw new ErrorException("All Log data provided are empty or invalid!");
  115. }
  116.  
  117. $sql = "INSERT INTO `{$this->dbTbl}` (".implode(",", $query_values).") VALUES (".( implode( ",", str_split( str_repeat( "?", count( $query_values ) ) ) ) ).")";
  118.  
  119. $stmt = $this->db->prepare($sql);
  120.  
  121. $fmts = implode("", $params_format);
  122.  
  123. $stmt->bind_param($fmts, ...$params_values);
  124.  
  125. $executed = $stmt->execute();
  126.  
  127. if($executed){
  128.  
  129. $resp = [
  130. "status" => "success"
  131. ];
  132.  
  133. }else{
  134.  
  135. $resp = [
  136. "status" => "error",
  137. "sql" => $sql,
  138. "queries" => $query_values,
  139. "formats" => $fmts,
  140. "values" => $params_values,
  141. ];
  142.  
  143. }
  144. return $resp;
  145. }
  146.  
  147. /**
  148.   * Log Data
  149.   * @param $user_id mixed|int User ID
  150.   * @param $action str Action Data
  151.   */
  152. public function setAction($user_id= "", $action = ""){
  153. $data = [];
  154.  
  155. extract($_SERVER);
  156. $data['ip'] = $REMOTE_ADDR;
  157. $data['url'] = (empty($HTTPS) ? 'http' : 'https') . "://{$HTTP_HOST}{$REQUEST_URI}";
  158. $data["user_id"] = $user_id;
  159. $data["action"] = addslashes(htmlspecialchars($action));
  160.  
  161. return $this->log($data);
  162. }
  163.  
  164. /**
  165.   * Get All Logs
  166.   */
  167. public function getLogs(){
  168.  
  169. $query = $this->db->query("SELECT * FROM `{$this->dbTbl}` order by `id` desc");
  170. $result = $query->fetch_all(MYSQLI_ASSOC);
  171.  
  172. return $result;
  173. }
  174.  
  175. function __destruct()
  176. {
  177. if($this->db){
  178. $this->db->close();
  179. }
  180. }
  181. }
  182. ?>

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:

  1. <?php
  2. $dbData = [
  3. "localhost", // Hostname
  4. "root", // Username
  5. "", // Password
  6. "dummy_db" // DBName
  7. ];
  8. $activityLog = new ActivityLog(...$dbData);
  9. $activityLog->setAction($_SESSION['user_id'], "accessed the home page");
  10. ?>

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.

Snapshots

Explore the snapshots below, showcasing the Sample Web Application I created:

Customer List

Implementing an Activity Log in PHP

Customer Form Modal

Implementing an Activity Log in PHP

Activity Logs

Implementing an Activity Log in PHP

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:

Happy Coding =)

Add new comment