Using File Writing To Log Errors In Your PHP Application

/ PHP / by Paul Robinson / 0 comments
This post was published back on May 6, 2010 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

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.

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more