Php session log file

How to create a logfile in php

I want to create a logfile for my system to register/log every action they do inside the system. But I have no idea how to do it. For example, I have this php code that does the login function.

public function hasAccess($username,$password)< $form = array(); $form['username'] = $username; $form['password'] = $password; $securityDAO = $this->getDAO('SecurityDAO'); $result = $securityDAO->hasAccess($form); //var_dump($form); //var_dump($result); 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); > > 

now I want to create a logfile entitled ‘the date today’, then when that functions is used for loging in, it will write that user has logged in, the same with other functions. But I only want a single file for every day. Could anyone be kind enough to guide and teach me how I should do my code?

11 Answers 11

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); > > 

I tried to put my system on a linux based computer and now there’s a problem with the log file regarding permissions. How can I fix it?

Читайте также:  Php comments commenting in php

Adding on to this: «PHP_EOL is like doing «\n» or «\r\n» dependent on which os platform. I hate lots of \n\n\n\n’s ;p – Lawrence Cherone Nov 11 ’13 at 4:55 » EOL simply stands for End of Line. Available since PHP 5.0.2. Read more here : php.net/manual/en/reserved.constants.php

Especially log files. There are plenty of applications that ask for a password to be stored in a plaintext config file, that’s a pretty well accepted norm. The folders that contain these files need to be locked down permissions wise though and those should only ever be service-specific passwords, never, ever real blood-n-bone user passwords.

the code isn’t safe against concurrent writes, if there’s 2 scripts trying to write to the log at the same time, and script 1 has so much data that not all of the data is written in a single write() (whereupon file_put_contents will automatically do a 2nd write() to try to write the remaining data), and script #2 write its log after the 1’st scripts 1st write, but before script1’s 2nd write(), the logs will be mangled — you can avoid that potential issue by using LOCK_EX in combination to FILE_APPEND (or’ed together, bitflags), then script2 will wait for script1 to finish completely

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"); 

Agree with the @jon answer. Just added modified the path to create the log directory inside the root

 function wh_log($log_msg) < $log_filename = $_SERVER['DOCUMENT_ROOT']."/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'; file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND); > wh_log('log to file'); 

just added $_SERVER[‘DOCUMENT_ROOT’]

Please check with this documentation.

 // Notify administrator by email if we run out of FOO if (!($foo = allocate_new_foo())) < error_log("Big trouble, we're all out of FOOs!", 1, "operator@example.com"); >// another way to call error_log(): error_log("You messed up!", 3, "/var/tmp/my-errors.log"); ?> 

Please check this code, it works fine for me.

$data = array('shopid'=>3,'version'=> 1,'value=>1'); //here $data is dummy varaible error_log(print_r($data,true), 3, $_SERVER['DOCUMENT_ROOT']."/your-file-name.log"); //In $data we can mention the error messege and create the log 

In above code error_log line is enough to create a new log file in your root folder, print_r($data,true) data mention what you are really want to print in that log file.

You could use built-in function trigger_error() to trigger user errors/warnings/notices and set_error_handler() to handle them. Inside your error handler you might want to use error_log() or file_put_contents() to store all records on files. To have a single file for every day just use something like sprintf(‘%s.log’, date(‘Y-m-d’)) as filename. And now you should know where to start. 🙂

How do I write it? Do you mind if you could give me a sample code? If it’s not too much to ask. Thank you.

This is my working code. Thanks to Paulo for the links. You create a custom error handler and call the trigger_error function with the correct $errno exception, even if it’s not an error. Make sure you can write to the log file directory without administrator access.

 $filename = basename($errfile); switch ($errno) < case E_USER_ERROR: file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "ERROR >> message = [$errno] $errstr\n", FILE_APPEND | LOCK_EX); exit(1); break; case E_USER_WARNING: file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "WARNING >> message = $errstr\n", FILE_APPEND | LOCK_EX); break; case E_USER_NOTICE: file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "NOTICE >> message = $errstr\n", FILE_APPEND | LOCK_EX); break; default: file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "UNKNOWN >> message = $errstr\n", FILE_APPEND | LOCK_EX); break; > // delete any files older than 30 days $files = glob($logfile_dir . "*"); $now = time(); foreach ($files as $file) if (is_file($file)) if ($now - filemtime($file) >= 60 * 60 * 24 * $logfile_delete_days) unlink($file); return true; // Don't execute PHP internal error handler > set_error_handler("error_handler"); trigger_error("testing 1,2,3", E_USER_NOTICE); ?> 

Источник

I want to save full session log in text file using php

I would like to save full session logs in text per each day. here is my code to create file and save log.

session_start(); if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) < header("location: index.php"); //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: ".($_SESSION['SESS_USER_ID']).PHP_EOL. "User Type: ".($_SESSION['SESS_USER_TYPE']).PHP_EOL. "-------------------------".PHP_EOL; //- file_put_contents('./log_'.date("j.n.Y").'.txt', $log, FILE_APPEND); //exit(); >$expiry = 60;//session expiry required after 30 mins if (isset($_SESSION['LAST']) && (time() - $_SESSION['LAST'] > $expiry)) < session_unset(); session_destroy(); header("location: logout.php"); >$_SESSION['LAST'] = time(); 

Its not creating any file so can anyone help me to save session login time, logout time & session activity in text file in root directory

Is there any errors ? Could you add error_reporting(E_ALL); ini_set(‘display_errors’, true); at the start of your script ?

Its displays Warning: file_put_contents(log_31.8.2016.txt) [function.file-put-contents]: failed to open stream: Permission denied in /var/www/html/auth.php

Here you go, you don’t have the permission to write a file in that directory. What’s the server’s OS ?

Источник

Populating remote user in apache log files from PHP session

I used to be passable at C programming — so I could write my own if necessary — unfortunately a lot of the links from https://modules.apache.org are dead (mod_auth_any, mod_auth_cookie_dbm) so I’m having trouble finding something close to what I need to understand the API / finding something which I could use out of the box.

Any suggestions of well written modules which might provide what I need, or which are close to my requirements and well written/maintained?

2 Answers 2

The wiki contains a lot of useful informations, like:

Cookies could be used but:

It is not possible to set cookies from an authentication module

And no cache of authentification is done (only mod_authz_ldap is having a server-side cache).

I think you’ll need to handle the PHP session initialization (cookie set), login pages, retry pages, and login succes (with maybe a session id regeneration) in a separate application, dedicated to that work. Use a second virtualhost, doing only that, like you would have with a SSO solution like CAS or a Radius server. Then use mod_auth_external to check the given cookie content or redirect the user to that login application. In the mod_auth_external authenticator you’ll have to control it’s a valid session on the server side (do not trust cookie content), either directly on the database or with a communication with this second app), but you should find something running fast, it’s done on every requested object. Or trust the cookie content, using it for loging purpose only, but do not trust it on your real PHP application and check that the session is valid in the real application PHP side.

Источник

Оцените статью