Output a Snapshot of All Defined Variables in PHP

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

<?php echo ‘<pre>’; print_r(get_defined_vars()); echo ‘</pre>’; ?>

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.

<?php echo ‘<!–’; print_r(get_defined_vars()); echo ‘–>’; ?>

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?

Actions
  • Comment
  •   Subscribe

Comments

2 Responses to “Output a Snapshot of All Defined Variables in PHP”

  1. Diaan on February 10th, 2009 7:56 am

    Very nice and super helpful. Thanks for this!

  2. James on February 17th, 2010 9:23 am

    Quality mate, hadnt seen this function before, much appreciated

Share Your Thoughts