Using File Writing To Log Errors In Your PHP Application
Most of the time when developing an application you don’t want to display nasty error messages to users, so you turn on error logging and turn off display errors in your PHP.ini file to take care of logging syntax errors that occur to file. The problem is that in these days of complex applications you need to log custom errors that occur, but you don’t want to display technical information to users. To solve this we write technical information to a log file, just like PHP can write errors to file when it’s enabled in the PHP.ini.
Writing To File
First let’s look at how to write something to file using PHP.
1 2 3 |
$fp = fopen('file.ext', 'at'); fwrite($fp, $data); fclose($fp); |
That is how to write to a file in PHP. Let’s go through what exactly is happening before we move on. On line 1
we run fopen
this tells PHP to open the file we want to write to. The at
is a set of modes, in this case append & text mode. For a full list check out the PHP documentation page for fopen
. Next is fwrite
. If you’ve guessed that fwrite
writes data to the file, then you’d be correct. Finally we close the file using fclose
.
Logging Errors
Let’s assume for a second that we already have an application. Now this application shouldn’t break, but as you know we still need to assume that it will. So let’s make it log variable information to file, and then give the user a nice friendly message.
1 2 3 4 5 6 7 8 9 10 11 |
//array of variable data. The stuff we need to see to help fix our error. $data = array('key1' => 'item1', 'key2' => 'item2', 'key3' => 'item3'); if($error) { $logout = "------- " . date('y m d H:i:s') . " -------\n"; $logout .= print_r($data, true); $fp = fopen('debug.txt', 'at'); fwrite($fp, $logout); fclose($fp); //display our user friendly error... } |
I have omitted the display the friendly error as that part would depend entirely on your application. What we have done is used the file writing code I showed earlier and used it to append an error onto the end of the debug file. If it’s the first error then PHP will create the file. Also the great thing about using print_r
is that it will pre-format the information, so if you open the file in something like Notepad++ it will display with nice human readable spacing.
I hope that little look at logging errors to file helps in some way. While it’s important to keep usability at the top of your list, it’s also good to remember to give yourself as much information as possible to debug any errors that crop up. Logging debug information to file is, in my opinion, an invaluable way to help.
As always any questions, or problems let me know in the comments, or you can follow me on Twitter. Just click the big blue birds in the sidebar.