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.
1 2 |
$file = 'log.txt'; file_put_contents($file,'logged value:'.$myVariable); |
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):
1 2 |
$file = 'log.txt'; file_put_contents($file,'logged value:'.$myVariable, FILE_APPEND | LOCK_EX); |
If you need to write an array use the following format:
1 |
file_put_contents($file,'logged value:'.print_r($myArray,true)); |
This is great! Helped me much with debugging ajax accessed PHP files.
Thanks