PHP debugging and logging using file_put_contents

There are many ways to debug code. Obviously, the most in-depth debug process is using a full blown debugger such as xDebug (more information can be found here).
Othertimes we simply use echo() or die() statements in order to peek into variables.

Here I would like to show another simple way to debug/monitor values or processes while avoiding interruption to the running code.

file_put_contents() is a shortcut to opening a file, writing data into that file and closing it.
As parameters you can pass a filename you want to use for logging/debugging and the values which you want to save in that file.

Let’s say I have a function that runs several times and I need to know the value of a variable inside my loop, but want to avoid sending text to the screen. I can log its value with file_put_contents() and check the file content immediately at the end of the run for the result.

The above code will create a new file if it doesn’t exist and overwrite its content with the value of $myVariable .

There’s also an option to append new content to the existing one (LOCK_EX flag prevents writing to the file at the same time):

If you need to write an array use the following format:

 

One comment

Leave a Reply

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