Logging: A quick and simple way to log output in PHP

If you’ve ever used JavaScript or jQuery, then you’ve probably been spoiled by the built-in console that comes with most modern web browsers. A quick call to console.log() is all it usually takes to quickly inspect your data, providing a fast and invaluable debugging tool while you’re developing your project.

Unfortunately, being a server-side language, PHP isn’t afforded the same luxury, and although plenty of solutions do exist to solve this problem, most of them are often overkill when all you want to do is peek at an array or the contents of a variable during code execution. Debuggers and Unit Testers are available in many IDEs, which are great for complex object-oriented code and when you need to do more than just peek at a value, but more often than not, I find myself using this;

It’s probably one of my most-used code-snippets, because the majority of the time I just want to ensure the data I’m returning from a database query is correct, or that an array I’ve dynamically-built contains the correct data in the right structure. It means I can make alterations quickly, when stepping through a debugger or setting up Unit Tests would take longer. The pre tags ensure the browser preserves spacing and line-breaks, and print_r() provides a nice clean readable format for arrays;

Although this method can be quick, it can also be inconvenient to stop the entire execution of your project. Sometimes however this is unavoidable, especially when working with MVC frameworks, as the final page your browser displays might not be the one you’ve printed your output to. You may wish to see output from your controller or your model, but without stopping execution flow, your application may render your view and prevent you from seeing your test output. Then there’s production code. If you have no other options than to work directly on a live system, then die() is one of the last functions you’d want to use.


A more elegant solution would be to create a helper class that would allow you to log data at any stage during your application.

Then call the static method, passing in your array or variable;

The method will append to the log by default, unless you pass in a different mode. It will generate a html log file in the source directory of the class. You can of course change this if you wish to output your log within a particular directory. Reloading the log is then just a simple matter of hitting refresh in your browser.


While these quick code snippets are by no means a solution to every debugging problem you’ll face, they’re still a useful and time-saving strategy when you need quick access to variable output.

Leave a Reply

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