How to create a logfile in php
Solution 1:
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);
}
}
Solution 2:
create a logfile in php, to do it you need to pass data on function and it will create log file for you.
function wh_log($log_msg)
{
$log_filename = "log";
if (!file_exists($log_filename))
{
// create directory/folder uploads.
mkdir($log_filename, 0777, true);
}
$log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
// if you don't add `FILE_APPEND`, the file will be erased each time you add a log
file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
}
// call to function
wh_log("this is my log message");