How to Create Complete Log With PHP

When we want to keep tracking of events performed in web applications then we need to save logs for it. 

There are mainly 2 approaches used to save logs to track user events. The one is to save the log file and the other is to save in the database.

Generally, the developer saves the IP address and request parameters in DB.

In this tutorial, I am going to show you how to save a complete log with PHP.

This approach will help you to add complete information related to a particular event performed in web applications.

Let’s see how to create a complete logs guide.

Use a database to store custom logs. 

You can use your database to create a table to save the complete log.

Create a Database Table

We have created the database or selected already existing. In this step, we will create a table to store log. 

You can copy below given query and use it in the SQL query option in PHPMyAdmin to create a table.

CREATE TABLE complete_log ( id int(11) NOT NULL, userid int(11) DEFAULT NULL, platform varchar(30) DEFAULT NULL, server text, request text, logtime timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Function for Adding Log to Database

In this step, we create a function file that we include on every page where we want to add log. 

Create a file name functions.php

<?php 
//Connect to MySQL database
$con = mysqli_connect('host_name','user_name','password','db_name');
if (mysqli_connect_errno($con)) { trigger_error('Database connection failed: ' . mysqli_connect_error()); }

//function to call on every page
function addCompleteLog($postvalues) {
global $con;
$query = "INSERT INTO `complete_log` SET";
foreach ($postvalues as $key => $value) {
$query .= "$key='$value'"; $query .= ",";
}
$query = substr($query, 0, -1);
mysqli_query($con, $query);
$this->id = mysqli_insert_id($con);
return $this->id;
}
?>

Usage

The example below illustrates how to use this function. Call the function when you want to add a complete log.

<?php 
include_once('functions.php');
$postvalues = new stdClass();
$postvalues->userid = $userid;
$postvalues->server = json_encode($_SERVER);
$postvalues->request = json_encode($_REQUEST);
$postvalues->platform = 'WEB';
addCompleteLog($postvalues);
?>

This approach is good for those devs who want to store complete information in logs. If you want to add custom information then you can use it as per your requirements.

I hope you have understood how to add complete logs in PHP. If you have any queries related to this tutorial feel free to comment.

Leave a Comment