The following line of code is one of the most useful diagnostic tricks in my PHP coding arsenal:

’; print_r(get_defined_vars()); echo ‘’; ?>

Simply input the above snippet of code into any PHP file and you’ll get a browser-friendly snapshot of all variables defined in the current scope. This is especially handy in larger systems like WordPress or Smarty where a needed value may already be defined by the system but you have no way of knowing the variable’s name.

With a slight variation, you can even use this trick on live systems without alerting ordinary users to the output.

’; ?>

This will produce the same output but limit its visibility to those viewing the source code.

In either case, be sure not to leave code like this active for longer than necessary, since a hacker could potentially use it to exploit your website.

Do any of you PHP coders out there have some similarly useful debugging tricks to share with the rest of us?

4 thoughts on “Output a Snapshot of All Defined Variables in PHP

  1. As a side note, I discovered recently that the print_r() function actually takes a second, boolean argument that determines whether the readable format should be returned instead of printed. This is particularly useful on system such as Drupal where it’s often more useful to do something like this:

    drupal_set_message(‘<pre>’ . print_r(get_defined_vars(), 1) . ‘</pre>’);

Leave a Reply

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