Simple Logging in PHP (File based & one-liner)
Often we (php developers) need to log certain messages in order to debug our script. Here I will describe the default syslog method and a much simpler (and better) way to log your messages quickly and painlessly.
PHP manual suggests using syslog for logging.
Problems with syslog
The problem with syslog is that its implementation is system dependent. For example openlog() is not supported on windows.
The location of the logged data is system dependent, which you may not have access to (if you are on a shared web hosting environment) or know about.
The procedure is more cumbersome than you may like to undertake for simple quick and dirty log messages.
Using syslog
Here is a sample code using syslog:
< ?php
define_syslog_variables();
// open syslog, include the process ID and also send
// the log to standard error, and use a user defined
// logging mechanism
openlog("myScriptLog", LOG_PID | LOG_PERROR, LOG_LOCAL0);
// some code
if (authorized_client()) {
// do something
} else {
// unauthorized client!
// log the attempt
$access = date("Y/m/d H:i:s");
syslog(LOG_WARNING, "Unauthorized client: $access $_SERVER[REMOTE_ADDR] ($_SERVER[HTTP_USER_AGENT])");
}
closelog();
?>
Simpler alternative
Now lets look into a quicker and simpler alternative for your simple logging needs.
file_put_contents('log_file_name', $data, FILE_APPEND);
$data is the data you want logged. You can also pass in an array. This creates a file in the directory the script is invoked from and appends your log messages.
Filed under Headline News, How To, PHP, Tech Note, Web, Web Services, Windows |
3 Comments |
Email this Article


















August 23rd, 2006 at 1:24 pm
[...] articles on Open Source Software, PHP, Web, WebLog, How To, Headline News, Tech Note | | RSS 2.0 | Trackback this Article | Email thisArticle [...]
September 11th, 2007 at 11:44 pm
Thanks a zillion for this hint!
It\’s EXACTLY what I needed. I hope there isn\’t some kind of exploit as it almost seems too good to be true.
[it also makes for a nice alternative to logging services that add cookies and such. I mean, I use \’em - I like to know what keywords are used, how many pages, entry and exit pages and all of that — but sometimes… sometimes you just want a stinkin\’ IP address!!
I\’m a microsoft excel NUT, so I like to be able to have massive amounts of data to sort through and make my own graphs, charts, filters, ideas, implementations.
Your one little line of code is just what the doctor ordered.
Ken of Naples FL USA - grateful.
September 12th, 2007 at 8:41 pm
This isn’t an exploit