downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

About debugging in PHP> <Comparing objects
[edit] Last updated: Fri, 22 Jul 2011

view this page in

Debugging in PHP

Table of Contents



About debugging in PHP> <Comparing objects
[edit] Last updated: Fri, 22 Jul 2011
 
add a note add a note User Contributed Notes Debugging in PHP
dcz at phpbb-seo dot com 18-Mar-2011 10:32
Here my little contribution for a simple yet handy debug function :
<?php
/**
* dbug (mixed $expression [, mixed $expression [, $... ]])
* Author : dcz
* Feel free to use as you wish at your own risk ;-)
*/
function dbug() {
    static
$output = '', $doc_root;
   
$args = func_get_args();
    if (!empty(
$args) && $args[0] === 'print') {
       
$_output = $output;
       
$output = '';
        return
$_output;
    }
   
// do not repeat the obvious (matter of taste)
   
if (!isset($doc_root)) {
       
$doc_root = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
    }
   
$backtrace = debug_backtrace();
   
// you may want not to htmlspecialchars here
   
$line = htmlspecialchars($backtrace[0]['line']);
   
$file = htmlspecialchars(str_replace(array('\\', $doc_root), array('/', ''), $backtrace[0]['file']));
   
$class = !empty($backtrace[1]['class']) ? htmlspecialchars($backtrace[1]['class']) . '::' : '';
   
$function = !empty($backtrace[1]['function']) ? htmlspecialchars($backtrace[1]['function']) . '() ' : '';
   
$output .= "<b>$class$function =&gt;$file #$line</b><pre>";
   
ob_start();
    foreach (
$args as $arg) {
       
var_dump($arg);
    }
   
$output .= htmlspecialchars(ob_get_contents(), ENT_COMPAT, 'UTF-8');
   
ob_end_clean();
   
$output .= '</pre>';
}
?>

usage :
<?php
dbug
($scalar, $array, $object, $resource, CONSTANT);
//..
dbug($other);
//..
echo dbug('print'); // actually output the result of all previous calls
// looks like :
// class::method() =>/path/from/doc/root/file.php #line
// var_dump result

?>

I found it handy not to directly output result data because this makes it possible to debug variables before headers are sent (useful for pre sessions start code for example).
morten sickel 17-Feb-2011 06:39
In my debug function I added some functionallity to print out from where the function was called:

<?php
function debug($value=''){
   
$btr=debug_backtrace();
   
$line=$btr[0]['line'];
   
$file=basename($btr[0]['file']);
    print
"<pre>$file:$line</pre>\n";
    if(
is_array($value)){
        print
"<pre>";
       
print_r($value);
        print
"</pre>\n";
    }elseif(
is_object($value)){
       
$value.dump();
    }else{
        print(
"<p>&gt;${value}&lt;</p>");
    }
}
?>

Thereby it is easy to keep the overview if you debug more variables simultaneously or, if the program crashes somewhere, just throw in a few debug() and you'll easily see how far the program comes
frank at silverwolfmedia dothere com 19-Nov-2009 12:23
I always include debugging code in all may major projects. I use an object (e.g. $CFG) to store the settings the control the code's behavior, which includes a $CFG->debug variable to control the level of debugging verbosity. I set it to 0 before rollout, which ensures that even if some debugging code was left in accidentally, this will be deactivated and not spew debugging information in a live website.

I use the following functions to facilitate debugging messages. They live in a single code module which I only need include() to use it. Note the global reference to $CFG:

<?php
// Dump the contents of a variable into HTML comments for debugging:
function debugVar ($var) {
  global
$CFG;

  if (
$CFG->debug) {
    echo
"\n<!--\nDEBUG INFO: \n";
    if (
is_array ($var))
     
print_r ($var)
    else
     
var_dump ($var);
    echo
"\n-->\n";
  }
}

// Dump function parameters into HTML comments for debugging:
function debugFunc () {
  global
$CFG;

  if (
$CFG->debug) {
   
$argv = func_get_args ();
    echo
"\n<!--\nDEBUG INFO: \n";
   
print_r ($argv);
    echo
"\n-->\n";
  }
}

// Dump a debugging message into HTML comments for debugging:
function debugMsg ($msg) {
  global
$CFG;

  if (
$CFG->debug) {
    echo
"\n<!--\nDEBUG INFO: \n";
    echo
$msg;
    echo
"\n-->\n";
  }
}
?>

Usage is simple:

To check a variable, call <?php debugVar ($variable); ?>

To check  parameters passed to a function, call
<?php debugFunc ($var1, $var2, $var3 ...); ?>

To print a debug message, call
<?php debugMsg ("Function xyz returned " . $retVal); ?>

Then check your HTML source to find the debugging output in the comments.

Don't forget to set $CFG->debug to 0 before rollout. If you're paranoid you can also include a javascript alert() box to be triggered by a : $CFG->debug > 0" condition upon each page reload, although that gets really annoying really fast. :-)

// Frank
turaz dot w4l at gmail dot com 06-Aug-2009 11:14
I usually use this simple function in combo with a die(); in order to have on screen the value of a variable or array:

<?php
function debug_view ( $what ) {
    echo
'<pre>';
    if (
is_array( $what ) )  {
       
print_r ( $what );
    } else {
       
var_dump ( $what );
    }
    echo
'</pre>';
}
?>
tomboul 09-Apr-2009 10:51
Here a best printed var_dump : show_php
It's a reccursive function for output many kind of structured data (array, class, etc ...)

<?php
function show_php($var,$indent='&nbsp;&nbsp;',$niv='0')
{
   
$str='';
    if(
is_array($var))    {
       
$str.= "<b>[array][".count($var)."]</b><br />";
        foreach(
$var as $k=>$v)        {
            for(
$i=0;$i<$niv;$i++) $str.= $indent;
           
$str.= "$indent<em>\"{$k}\"=></em>";
           
$str.=show_php($v,$indent,$niv+1);
        }
    }
    else if(
is_object($var)) {

       
$str.= "<b>[objet]-class=[".get_class($var)."]-method=[";
       
$arr = get_class_methods($var);
           foreach (
$arr as $method) {
              
$str .= "[function $method()]";
           }
       
$str.="]-";
       
$str.="</b>";
       
$str.=show_php(get_object_vars($var),$indent,$niv+1);
    }
    else {
       
$str.= "<em>[".gettype($var)."]</em>=[{$var}]<br />";
    }
    return(
$str);
}
?>

EXAMPLE :

array example to debug :

<?php
$tab
=array(
   
"first"=>"firstValue",
   
"second"=>array(
       
"first"=>1,
       
"second"=>2,
       
"third"=>array(
           
"first"=>"one",
           
"second"=>"two"
       
),
    ),
);
?>

result of show_php :

<?php
echo "tab=".show_php($tab);
?>

tab=[array][2]
  "first"=>[string]=[firstValue]
  "second"=>[array][3]
    "first"=>[integer]=[1]
    "second"=>[integer]=[2]
    "third"=>[array][2]
      "first"=>[string]=[one]
      "second"=>[string]=[two]
     

result of var_dump :

<?php
echo "tab=";
var_dump($tab);
echo
"<br>";
?>

tab=array(2) { ["first"]=> string(10) "firstValue" ["second"]=> array(3) { ["first"]=> int(1) ["second"]=> int(2) ["third"]=> array(2) { ["first"]=> string(3) "one" ["second"]=> string(3) "two" } } }
Diego 18-Feb-2009 12:21
If you don't find a syntax error, you can comment out a block where you assume the error (or put it out of the document by [ctrl] + [X], but keep a copy on your HD for the case, your computer crashes) and check, if the syntax error is still there.
If not, it must be anywhere in your commented text; if yes, it must be somewhere else.
If you want to locate the error better, do it again with an other and/or smaller piece of code, till you get it.
online _ use _ only == hotmail.com 15-Mar-2006 11:41
I still find that printing out variable values at problem points in the code is one of the easiest ways for me to debug.  If you're interested in knowing the full contents of an object/array/scalar, then use

var_dump($var).

 
show source | credits | sitemap | contact | advertising | mirror sites