.Maui Blog

Small PHP class to write log files

Here is a small class in PHP to write log files. If the file name is not specified, it will be assigned by the script.

<?php
class Log {
    
    private $PATH;
    
    function __construct($file_name = null) {
        
        $this->PATH = $_SERVER['DOCUMENT_ROOT'] . "/log/";
        
        if (is_null($file_name)) 
            $file_name = date("dmYHis") . ".txt";
        
        $this->PATH .= $file_name;

        if(!$fileHandle = fopen($this->PATH, 'a+')){        
            return false;
        }   
    }
    
    public function write($txt) {        
        $fileHandle = fopen($this->PATH, 'a+');
        $message    = date('d/m/Y H:i:s') . ' - ' . $txt . "\r\n";  
        
        fwrite($fileHandle, $message);        
        fclose($fileHandle);
        
    }
    
}

How to use

<?php
$log = new Log();

$log->write("Lorem impsum");
$log->write("dolor sit amet");
Exit mobile version