Debug Variables in PHP

by damonp on August 22, 2005

in PHP,Snippets

Drop this function into a PHP include and use it to print out variable debugging info during runtime.

<?php
function dv($var, $var_name='', $remote_ip='') {
    if($remote_ip != '' && $remote_ip != $_SERVER['REMOTE_ADDR'])   return;
    $tab = strlen($var_name) > 6 ? "\t":"\t\t";
    $var_name = $var_name != '' ? '$' . $var_name . ' ' . $tab . ' = ':'';
    print('<pre> ' . $var_name);
    var_dump($var);
    print("</pre>\n");
}  
?>

To call, use one of the following:

<?php
dv($the_variable, 'the_variable_name', '192.168.0.1');
?>

Where:

  • $the_variable – the variable to print
  • the_variable_name – the name of variable to print
  • 192.168.0.1 – your local IP address. Variable will only be echoed when the page is called from this IP address. Useful for debugging on live sites.

The last two parameters are not required but can be used for additional flexibility.

If printing out the same variable at multiple locations in the same page, use successive names for the_variable_name (the_variable_name1, the_variable_name2, etc) to differentiate.

If debugging which file is being processing do:

<?php
dv(__FILE__, 'file', '192.168.0.1');
?>

This will echo the filename the function is called from.

If debugging which line the script stops processing on do:

<?php
dv(__LINE__, 'line', '192.168.0.1');
?>

This will echo the line number the function is called from.

Popularity: 3%

Most Popular Posts

Damon Parker is a freelance sysadmin and web developer in Texas. He specializes in server setup, server security and high performance server configurations. Need help setting up a web server or getting a server back online after a crash or hack? Email Damon

Leave a Comment

{ 1 trackback }

Previous post:

Next post: