create a log file to track events, errors, or any other information

create a log file to track events, errors, or any other information you need to record during the execution of your script. Here's a basic example of how you can create a log file:

17

Arun Kr.
12-Jun-24
<?php
// Define the file path for the log file
$logFile = 'path/to/your/logfile.txt';

// Message to be logged
$message = "Log this message.";

// Open the log file in append mode
if ($handle = fopen($logFile, 'a')) {
    // Get the current date and time
    $timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
    
    // Write the log message along with timestamp to the file
    fwrite($handle, "[$timestamp] $message\n");
    
    // Close the file handle
    fclose($handle);
} else {
    // Handle error if unable to open the log file
    echo "Unable to open log file for writing.";
}
?>

 

This script will append a message along with a timestamp to the specified log file. Make sure to replace 'path/to/your/logfile.txt' with the actual path where you want to store the log file.

Remember to set appropriate permissions on the directory where the log file is stored so that PHP can write to it.

 


 

To display the last line of the log file first, you can read the file into an array, reverse the array to reverse the order of lines, and then output the lines. Here's how you can modify the previous example to achieve this:

 
<?php
// Define the path to your log file
$logFile = 'path/to/your/logfile.txt';

// Read the entire file into an array, each element of the array represents a line
$lines = file($logFile);

// Reverse the array to display the last line first
$lines = array_reverse($lines);

// Output each line
foreach ($lines as $line) {
    echo $line . "<br>";
}
?>
@Since 2024 Arun'Log Powered by Arun Git