You can do it the OO way, just an alternative and flexible:
class Logger {
private
$file,
$timestamp;
public function __construct($filename) {
$this->file = $filename;
}
public function setTimestamp($format) {
$this->timestamp = date($format)." » ";
}
public function putLog($insert) {
if (isset($this->timestamp)) {
file_put_contents($this->file, $this->timestamp.$insert."<br>", FILE_APPEND);
} else {
trigger_error("Timestamp not set", E_USER_ERROR);
}
}
public function getLog() {
$content = @file_get_contents($this->file);
return $content;
}
}
Then use it like this .. let's say you have user_name
stored in a session (semi pseudo code):
$log = new Logger("log.txt");
$log->setTimestamp("D M d 'y h.i A");
if (user logs in) {
$log->putLog("Successful Login: ".$_SESSION["user_name"]);
}
if (user logs out) {
$log->putLog("Logout: ".$_SESSION["user_name"]);
}
Check your log with this:
$log->getLog();
Result is like:
Sun Jul 02 '17 05.45 PM » Successful Login: JohnDoe
Sun Jul 02 '17 05.46 PM » Logout: JohnDoe