Synook

Useful PHP debugging functions

While we all wish that we could program in PHP without making any mistakes, sometimes we do encounter bugs that prevent our scripts from running correctly. When this happens, we have to debug, however, especially when programs get very big, trying to figure out the source of the errors can get very confusing. Nevertheless, PHP provides some useful functions to help in the debugging process. Some the ones I find particularly useful are detailed below.

  • print_f(): this function just prints out the value of the argument. However, unlike a simple echo it will display the contents of non-scalar variables such as arrays and objects.
  • var_dump(): similar to print_f(), however this function will display more detailed information about the variable passed, such as its length and data type.
  • debug_backtrace(): generates complete information about the function stack at the time of the debug_backtrace() call.
  • error_reporting(): temporarily sets a custom level of error reporting at runtime. Many hosts have error reporting set to 0, which is a good thing to do in live environments, but if you are using such a host for development, it is better to set the error level to E_ALL, so you can actually see what is going wrong instead of having scripts fail silently.

Of course, there are many other functions within PHP that can help you debug specific problems, such as mysql_error() for problematic database queries, however the above are four general functions that I have found can help in most cases.