handle = false; // Too dangerious, so return false } else { if (! is_dir(PROJECT_LOGS_DIR)){ //Directory does not exist, so lets create it. mkdir(PROJECT_LOGS_DIR, 0775); } $filename = preg_replace("|[^A-Za-z0-9_]|", "", $filename); $filename = escapeshellcmd($filename); $file = PROJECT_LOGS_DIR . '/' . $filename . ".log.txt"; if ($max_count > 1) { if ($this->get_lines($file) > $max_count) { unlink($file); } } $success = touch($file); if ($success === false) { $this->handle = false; return false; } chmod($file, 0660); if (! is_writable($file)) { $this->handle = false; return false; } $this->handle = fopen($file, 'a'); } } /** * Count number of lines in Log File * @param string $file * @return int line count */ public function get_lines(string $file): int { // No such file, so return zero for length. if (! file_exists($file)) { return 0; } $f = fopen($file, 'rb'); $lines = 0; if ($f === false || !is_resource($f)) { return 0; } while (!feof($f)) { $line = fread($f, 8192); if ($line === false) { return 0; } $lines += substr_count($line, "\n"); } fclose($f); return $lines; } /** * Write to Log File * @param string $message to save * @return bool able to write to log file */ public function write(string $message): bool { if ( $this->handle === false || ! is_resource($this->handle) ) { return false; } $tz = configure::get('logger_time_zone'); if ($tz !== false && !empty($tz)) { $tz_obj = new \DateTimeZone($tz); $dt = new \DateTime(); $dt->setTimezone($tz_obj); $now = $dt->format('g:i A \o\n l jS F Y'); } else { $dt = new \DateTime(); $now = $dt->format('g:i A \o\n l jS F Y'); } fwrite($this->handle, $now . ' - ' . print_r($message, true) . "\n"); return true; } /** * Close Log File Handle */ public function __destruct() { if ($this->handle !== false && is_resource($this->handle)) { fclose($this->handle); } } } // end of Logger