How to create log files in PHP & jQuery

In computing, a log file is a file that records every events. Most of the times they are system generated.

In web development , a developer can create an activity log. The point of a log file is to keep track of what’s happening behind the scenes.

In the broadest possible terms, an activity log is a list of all actions taken by every user on a given system. For example, when used on a WordPress website, this log would record every time a post was added or edited when a user attempted to log in, whenever the site was updated, and much more.


Here , we will create a log file for an admin. Log file will contain ip address, username, current date.

PHP code:

$username = $_SESSION[‘username’]; //I will suggest to store username in session after log in
date_default_timezone_set('Asia/Kolkata');
$current_date = date('d-m-Y h:i:s A');// Returns the date and time
$ip_address = $_SERVER['SERVER_ADDR'];// Returns the name of the host server
logoutLogFile($ip_address, $username, $current_date);


Js code:
function loginLog($ip_address, $username, $current_date)
  {
    //you may change the path
    $file_pointer = "logFiles/loginLogfile.csv";
      //to check wheather the file is exist or not
    if (file_exists($file_pointer)) 
    {
      // To open file for write, with pointer location at end of file
      $myfile = fopen("pages/log_files/login_logfile.csv", "a+") or die("Unable to open file!");
      // fwrite is used to write/append data to log file
      fwrite($myfile, $txt);
      $txt = $ip_address.", ".$username.", ".$current_date."\n";
      fwrite($myfile, $txt);
    }
    else 
    {
      // To create file for write, with pointer location at end of file
      $myfile = fopen("pages/log_files/login_logfile.csv", "a+") or die("Unable to open file!");
      // Store Log as string
      $txt = "IP Address, Username, Current Date\n";
      // fwrite is used to write/append data to log file
      fwrite($myfile, $txt);
      $txt = $ip_address.",".$username.",".$current_date."\n";
      fwrite($myfile, $txt);
    }
    // Close file 
    fclose($myfile);
  }



Output:

Did you like our works?

Here is your content of the callout box lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.