How to Write to Error Log File in PHP

How to create a logfile in php

To write to a log file and make a new one each day, you could use date("j.n.Y") as part of the filename.

//Something to write to txt log
$log = "User: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
"Attempt: ".($result[0]['success']=='1'?'Success':'Failed').PHP_EOL.
"User: ".$username.PHP_EOL.
"-------------------------".PHP_EOL;
//Save string to log, use FILE_APPEND to append.
file_put_contents('./log_'.date("j.n.Y").'.log', $log, FILE_APPEND);

So you would place that within your hasAccess() method.

public function hasAccess($username,$password){
$form = array();
$form['username'] = $username;
$form['password'] = $password;

$securityDAO = $this->getDAO('SecurityDAO');
$result = $securityDAO->hasAccess($form);

//Write action to txt log
$log = "User: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
"Attempt: ".($result[0]['success']=='1'?'Success':'Failed').PHP_EOL.
"User: ".$username.PHP_EOL.
"-------------------------".PHP_EOL;
//-
file_put_contents('./log_'.date("j.n.Y").'.txt', $log, FILE_APPEND);

if($result[0]['success']=='1'){
$this->Session->add('user_id', $result[0]['id']);
//$this->Session->add('username', $result[0]['username']);
//$this->Session->add('roleid', $result[0]['roleid']);
return $this->status(0,true,'auth.success',$result);
}else{
return $this->status(0,false,'auth.failed',$result);
}
}

Using php to write to a log file

Why not just use error_log()? With the message_type set to 3 (second parameter) the message will be written the the file specified in the third parameter:

$message = $_GET['w'];
$logfile = 'logfile.log';

// Debug: A line for verifying I have the message
echo "Writing message '$message' to logfile<br>";

error_log($message."\n", 3, $logfile);

// Debug: read back the log file to verify thatthe line has been written
readfile($logfile);

Note the newline appended to the message as error_log() doesn't do this for you.

Note also that permissions must be set to allow the web server to write to the target file. This is true whether using error_log() or file_put_contents()

PHP reference is here

Can't get PHP errors to go to a log file (other than the Apache log)

It had to do with ownership. One or the other has worked [for reasons that are not clear to me]:

chown www-data:www-data /var/log/php_error.log

chown same-user-as-www-home:same-user-as-web-home /var/log/php_error.log

Also, the following has made a difference:

chmod 664 /var/log/php_error.log

[as opposed to chmod 644...again for reasons that are not clear to me]



Related Topics



Leave a reply



Submit