Click to See Complete Forum and Search --> : Debugging 101


Bunkermaster
05-23-2003, 04:31 AM
As mentioned in a post I recently read http://www.phpbuilder.com/board/showthread.php?s=&threadid=10240313 (not all of it, it seams some people can't stop talking here so fast it's like IRC now) some people have NO IDEA whatsoever about debugging and actually finding errors so here are my useless hints :

1. When you code a MySQL query use new lines :
$sql = "SELECT
`yourtable`,`field1` as f1,
`yourtable`,`field2` as f2
FROM
`yourtable`
";
Why? If you have an error MySQL will give you line number referencing a line INSIDE the query. Always saves time to actually be able to use the info.

2. When you code a MySQL query echo it in a HTML comment (not in production) :
$sql = "SELECT
`yourtable`,`field1` as f1,
`yourtable`,`field2` as f2
FROM
`yourtable`
";
echo "<!--\n$sql\n-->";

Why? Well if your pages doesn't work try running your querries in phpMyAdmin or your DB manager and see the output. It sometimes is interesting.

More soon (tired now)

Bunkermaster
05-23-2003, 10:57 AM
add your tricks here, it is NOT c losed thread :D (or is it? /me checks) ok it is NOT a closed thread. Just use same coloring as i did so peeps can look at it fast

[COLOR=#FF8000] for tricks titles

Code goes inside [PHP] blocks :D

mystrymaster
05-23-2003, 03:12 PM
Comment closing brackets {}

if (isset($_COOKIE["me"])) {
Do all the code in here
if ($_COOKIE["me"] == 'poser') {
Do all the code in here
} else {
Do all the code here
} //Poser if
} else {
Do all the code here
} //Is Cookie Set



Why? Because as applications get more and more nested this will help you solve the unexpected $end on line number XXX error and will help you figure out where the close } is.

Bunkermaster
05-23-2003, 03:28 PM
Did a slight edit here to remove extra lines in code (shows double in FireBird each time... Annoying)

goldbug
05-23-2003, 04:02 PM
It's probably been mentioned before elsewhere, but when constructing strings, sql queries, whatever,....I prefer to escape out of the string (and use single-quotes where possible):

$moo = 'This is what ' . $cow . 'said to me.';

Instead of:

$moo = "This is what $cow said to me."


WHen using an editor that syntax-highlights, it makes it MUCH easier to pick out the variables (especially in large or complex strings).

Bunkermaster
05-23-2003, 06:59 PM
Yes goldbug but you have made the typical error :)

// No space after $cow
$moo = 'This is what ' . $cow . 'said to me.';
// Space after $cow
$moo = "This is what $cow said to me."

hehe but good one especially when embedding in HTML strings.

Mordecai
05-24-2003, 03:01 AM
Remove all headers when you are about to debug. Specifically if you are working on an image script. If you output a PNG (or another format) using header("Content-type: Image/PNG"), then no errors can be echoed. Errors can only be seen if something is text/html, not an image. This just results in a broken image, since PHP still echoes out the error.

Edit: Uhh.. I don't know how to use the board's code in the subject, so I took out the [color] thing.

xblue
05-24-2003, 08:10 AM
indent your code
this helps to detect missing braces, and can help to spot logical errors, too.

use an editor with syntax highlighting
makes it easy to find unclosed strings or unescaped quotes within string.

[bunkermaster, I think this might be more often needed in the newbie or general forum, maybe other moderators would be willing to place a reference there?]

barand
05-27-2003, 05:17 AM
Check variable contents

Use something like this to check you received what you expected to receive


echo '<pre>';
print_r ($_POST);
echo '</pre>';

Tekron-X
06-08-2003, 10:02 PM
WORK BACKWARDS

Most know this already but for those that don't...

When PHP spitts an error line and number out at you go from the line number given and if the error is not in that line work backwards.

The Reason for this is that PHP is not always accurate on its error line numbers.

GilesGuthrie
06-09-2003, 07:50 PM
Check for double-equals ==

If your conditional statement isn't working properly, and it's testing for equivalence, check that you've got two equals signs.

Weedpacket
06-14-2003, 08:18 AM
Originally posted by Tekron-X
The Reason for this is that PHP is not always accurate on its error line numbers. I wouldn't say that; I'd say that PHP reports the number of the line it was processing when it discovered that there was an error (if you miss out a }, PHP can't tell you where it should have been). So , depending on the error message, even if the error itself is not on the line indicated, that line may provide clues as to where the error actually is. For example, if it says that there was a type conversion error (where, say, an array was used where it expected a string), then one of the variables in that line is at fault: work backwards and see where they get their values from.

Weedpacket
06-15-2003, 12:45 AM
Leave using @ to suppress error messages until later.

When you tack an @ to the beginning of a function call, you prevent PHP from reporting any error messages the call generates. This feature was intended for use by people who want to write their own error-handling routines - e.g.: $foo = @bar() or choke('bar() is broken!', __FILE__, __LINE__);

While you're debugging, you want errors to be reported as soon as PHP realises there is one to report. Otherwise, your script will either just stop without giving any clue as to why, or it will try and keep running and most likely have more problems later on (and the error messages you get then would be less help).

So leave the @ off unless you are sure that you are properly handling any suppressed errors or you are sure that ignoring them won't cause any problems later.

Weedpacket
06-15-2003, 12:50 AM
Deal with the first error first.

If your script suddenly starts haemorrhaging dozens of Warning and Notice messages, it's not a cause for panic: it doesn't mean that you've got dozens of bugs to fix - it's more likely to be one bug causing dozens of errors.

Concentrate on the first error message reported and fixing the problem causing it; don't worry about the others too much. There's a good chance that whatever caused the first error message to be displayed is also responsible for making the mess that the other messages are talking about. Two causes for haemorrhages are that (1) the message is coming from a line inside a loop, and is being reported every time the loop is run through, and (2) the first error was caused by bad data; PHP continued to run, but that bad data caused more and more data to be corrupted and PHP became more and more confused about what to do with it.

Sometimes PHP's act of displaying an error message is itself enough to cause the other errors, especially if you're using one of the various header-manipulating functions, like header() or setcookie().

So fixing the first bug reported can make the others magically disappear.

With experience, you can use the other messages as additional clues to what went wrong in the first place; you can think of them as tracking the flow of corrupted data through the script.

philipolson
06-21-2003, 04:59 AM
Always code with E_ALL on and do not generate any errors.

Many functions return false on failure, you should check for that. One of the most common questions and errors is how people assume mysql_query() will return a valid MySQL resource 100% of the time. It won't. Instead you should check to make sure it doesn't return false, here's an example that demonstrates a few ways to check a functions returned value. I prefer to not use the 'or' operator (such as foo() or die(...)) as it's rather limiting but whatever, same idea:


<?php
error_reporting(E_ALL);

if (!$conn = @mysql_connect('localhost','user','pass')) {
echo 'Could not connect to MySQL: ' . mysql_error();
exit;
}

if (!@mysql_select_db('somedb')) {
echo 'Could not select db: ' . mysql_error();
exit;
}

// mysql_query returns false on failure
$sql = "SELECT foo,bar FROM stuff";
$result = @mysql_query($sql);
if (!$result) {
echo "Could not run query ($sql): " . mysql_error();
exit;
}

// If we expect rows, let's make sure some exist
if (mysql_num_rows($result) < 1) {
echo "No rows match your query, please try again";
exit;
}

// We know $result is valid, and rows exist to fetch
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
?>

The above isn't perfect but demonstrates basic error handling. Of course printing our sql queries and mysql errors isn't good in a production environment so consider showing prettier user friendly errors in production environments. For example, if no rows exist, consider telling them but including the search form again. Or creating/using db_error() that prints something differerent in "debug mode". @ is used to supporess PHP errors because we implemented out own error handling instead of relying on PHP's warnings. Anyway, the point is that mysql_query() (or whatever you're using) does sometimes fail and return false as our world isn't perfect, also, rows don't always exist to fetch.

FrozNic
06-24-2003, 05:32 PM
if u just can't figure out what the heck is wrong with ur code.. go watch southpark or simpsons for 10 mins, drink a quick md and eat a slice a pizza. go back to the comp. and suddenly ur prob will hit u in the face :) okay, i know it doesn't always work, but, u'd be surpised how often 10 mins of breathing room can do!

goldbug
07-14-2003, 04:08 PM
This isn't necessarily focused at just PHP:

When designing/coding an application, try to avoid hardcoding any proper nouns in anything (variable names, file names, site 'structures', etc...). It can be a huge pain in the ass to go back and change them later.

Example (which just so happens to be bothering me at work):

Your company's name is hardcoded into file names, contact addresses, what have you (recent situation: company name was hardcoded as the default "other" category for equipment -- used throughout code & database).
....... what happens when/if your company changes name or gets bought?

Not sure if that makes any sense, but I've found keeping things vague or non-possessive saves a LOT of time, down the line.

If this still doesn't make sense, just code your stuff as if you were to design something completely generic, as to be sold to many different people. All branding, names, logos should be easily modified in one place and accept drop-in replacements.

abx_2112
07-24-2003, 05:39 AM
Ok, this are some things that help me debug my scripts:

1. Keep trace of my vars: This is so important, and so basic. Sometimes the whole problem with your script is a typo which is ver frustrating.

I even have a dump function to be aware of the values on arrays, objects, post/get/session/etc vars .... It started looking something like this:

function dump($var, $label = '')
{
echo '<h1>'.$label.'</h1>';
echo '<pre>';
var_dump($var);
echo '</pre>';
}


Now am using some nice code I found here (http://www.zend.com/zend/tut/tutorial-DebugLib.php).

2. In order to reduce typos I avoid declaring more variables that i strictly need. A basic example:

/**
I dont like doing this kind of things:
*/
$date = time();
$log = $user_input . 'issued at' . $date;
my_function($log);

/**
Instead, try using something like this:
*/
my_function ($user_input . 'issued at' . time() );


The are some exceptions to this (see this article (http://www.zend.com/zend/art/mistake.php#Heading11) for details and some other very important stuff), but keep in mind this practices not only improve your scripts' performance, but reduces a lot of time while tracing a value.

3. Ok doing this all the time may result in some FREAKY code. That's why I use sprintf() when i need to give some formating or i see i have lots of function calls and stuff in the string.

$string = sprintf('
%s, keeping %f things readable
%d is easy %s',
foo( 'bar', implode($words, $_GET['token']),
$a - floor(rand($_apples)),
$counter/2,
$object->serialzeMe()
);

Get the point? Imagine doing the same thing concatenating all that stuff. That'll look horrible. Some people may find the use of sprintf unnecesary, but I personally like it.

that's it for now.

Hope this helps,
Abx_

JDunmyre
08-08-2003, 02:18 AM
DO get yourself into the habit of using a variable naming scheme, such as always capitalizing new words, using underscores, and using names that are relative to the variable.
This will give you an idea of exactly what's going on, if you see $Person_Index instead of $Blah
I bring this up because I was staring at code for a good half an hour before I noticed that I wrote $blah instead of $Blah for the index of an array. I looked everywhere for the error but the case of my variables!:eek:

tekky
08-10-2003, 10:05 AM
Originally posted by JDunmyre
DO get yourself into the habit of using a variable naming scheme, such as always capitalizing new words, using underscores, and using names that are relative to the variable.
This will give you an idea of exactly what's going on, if you see $Person_Index instead of $Blah
I bring this up because I was staring at code for a good half an hour before I noticed that I wrote $blah instead of $Blah for the index of an array. I looked everywhere for the error but the case of my variables!:eek:

the very reason why I practice
$vars = 'lowercase only';:D

Weedpacket
08-27-2003, 07:37 AM
Look at the script's output.

If your HTML page is coming out mangled in some way, have a look at the HTML source code the browser is receiving (most browsers will allow you to "View Source" - if you don't have one, get one). Sometimes it's not enough to just look at the rendered page.

All too often people post problems like "I want to print [stuff] on different lines but it all comes out on one line." or "my form variables are getting shortened". If these people viewed the source they'd probably see things like
<p>
I think I shall never see
An HTML page as pretty as me
</p> ("Oh, yes, that's right. HTML replaces line breaks with spaces. I need to turn those into <br> tags. That's nl2br.")

and

<input type=text value=First name last name=bunchawords>
("Ah, now I know why I'm supposed to quote my tag attribute values. How else is the browser supposed to know where the value ends and the next attribute begins?")

You might also find things like mislaid tags, discover that something that should have been inside a loop wasn't or vice versa, text HTML characters like < and > inside select options or textareas that is being mistaken for HTML (this is even easier in a browser that does sytnax highlighting in its view source window), and so on. (This last one happened to me today; HTML had accidentally got into the database and whenever that database field was printed out, the page went odd.)

Merve
09-06-2003, 05:08 PM
Functions and Arguments

This is a really dumb, but not so common error. Supplying incorrect arguments to functions. I've seen coding where someone tried to pass an array to explode()...doesn't work too well...

Also, when using your own functions, you might forget to supply arguments...very possible...I do that a lot, but I don't know if anybody else does.

Finally all constants are CAPITALIZED.

Wow that was simple stuff.

Moonglobe
09-20-2003, 12:56 AM
Check your configuration!
A little while ago i was coding a test site using Slabatron for XSLT............. only to find that my server didn't have the extension installed. always run phpinfo() if your not sure about your server's capabilities.

LordShryku
10-25-2003, 10:28 PM
SQL errors? Make sure none of your table's field names are named a MySQL Reserved Word (http://www.mysql.com/doc/en/Reserved_words.html)

sid
10-31-2003, 12:44 PM
if you dont get an actual error but the result you get is bogus, check what path your code is going (especially if it includes many nested structures):

simply print out a mark each time your code offers more thatn one option to walk through it, to see what it actually does:


<?php
if (...) {
print "<BR>mark 1<BR>";
while (...) {
print "<BR>mark 2<BR>";
if (...) {
print "<BR>mark 3<BR>";
}
elseif (...) {
print "<BR>mark 4<BR>";
forechach (...) {
print "<BR>mark 5<BR>";
}
}
else {
print "<BR>mark 6<BR>";
}
}
}
else {
print "<BR>mark 7<BR>";
}
?>



thisll give you a nice output like


mark 1

mark 2

mark 4

mark 5

mark 5


you can also print out variables on each mark to check the values... all over this is a very effective way to follow the path of your code and find out where could be a glitch (very handy for cases like (if $foo = 1) {...} )

dta
11-05-2003, 01:02 AM
more for php/javascript pages
check on multiple browsers

what javascript does on IE might not be the same on Netscape, etc.etc.

an added note, the builtin javascript debugger in Mozilla/Netscape is amazing if something in your script isnt what it should be

Merve
11-05-2003, 07:32 PM
Originally posted by LordShryku
SQL errors? Make sure none of your table's field names are named a MySQL Reserved Word (http://www.mysql.com/doc/en/Reserved_words.html)

MySQL reserved words

If you must use a MySQL reserved word for some strange and wacky reason, be sure to use backticks. If not absolutely necessary, this should be avoided.

njm
12-28-2003, 02:17 PM
Just a simple one:

All my code uses echo for outputting to the screen, but if I need to output something for debugging, then I use print instead, then when I go back over my code, I know easily which lines are real code and which I can take out.

Weedpacket
12-29-2003, 12:14 AM
Originally posted by njm
Just a simple one:

All my code uses echo for outputting to the screen, but if I need to output something for debugging, then I use print instead, then when I go back over my code, I know easily which lines are real code and which I can take out. Hey, nifty!
Reminds me of a practice I employ: exit() to stop the script processing because there's nothing more for it to do (e.g., after a header("Location:") call); die() to stop the script processing because something went wrong and it can't continue (e.g., the dbms has fallen over).

swr
01-02-2004, 01:29 AM
What philipolson said: use error_reporting(E_ALL).

It can be hard at first, because you'll probably have a whole bunch of code that works fine but when you turn up error_reporting to E_ALL it starts spewing "notice" messages like crazy.

It's worth it though, as you will end up saving lots of time in debugging. Things like mistyped variable names that would silently pretend to work and fail oddly at some later point in the code will now give you a notice message at exactly the line with the typo. Typos and similar bugs that used to cause hours of head-scratching can be found and fixed in seconds with error_reporting(E_ALL) enabled.

It does take some effort to avoid notices in innocent code. Namely, you need to use isset() or empty() to check if variables are okay. Most of these "needless" checks are related to form variables. I recommend creating a function (call it getvar or something) that gets form variables, handling all of the isset checking. It could substitute a default (like, an empty string) if no value is set so that you can avoid notices related to undefined values. Having a seperate function for getting form variables gives you the opportunity to do other things to, like checking the get_magic_quotes_gpc() setting and doing addslashes()/removeslashes() (whichever you prefer), allowing your code to work correctly no matter how the server is configured. Put this function and the error_reporting(E_ALL) call in a common include file and include it at the top of every script.

And remember: null and the empty string are not the same thing! '' is a string of zero length. null is the complete lack of any string or other value. PHP can automaticly convert null to '', leading novices to believe they are the same). Those automatic conversions generate a notice with E_ALL so be aware of the difference.

Merve
01-08-2004, 09:07 PM
break and continue are great and are often ignored. They can shorten code bigtime. Their optional numerical arguments are great. Without using them, one may end up really long code that is much harder to debug.

Tekime
05-31-2004, 12:05 AM
error levels

You may need to differentiate between error levels - such as errors generated by a form, a 'no results returned' error, etc. vs. system or database errors.

Use a generic error handler to customize error handling. You can already control error handling through PHP, but you might want generic application-level error handling. My scripts use a lot of templating stuff, but something along the lines of:

functions.php
function s_error($msg='Undefined Error', $kill=false, $priority=3, $log=false)
{
switch($priority)
{
case 1: // Alert the troops
log_error($msg,$priority);
sound_the_alarms($msg);
die('We might not be back for a bit.');
case 2: // Unrecoverable system error
if($log) log_error($msg,$priority);
die('System Error: ' . $msg);
case 3: // User / general error
if($log) log_error($msg,$priority);
echo "Sorry, an error occurred: " . $msg;
break;
default: // Or however else you want to handle this by default
die('Unspecified error');
}
return false;

}


Obviously, a lot more can be done with this, like handling error codes, formatting user errors, sending messages off to your mobile, etc. I check for an array in $msg and list multiple errors through a templater for example.

This way you can handle unrecoverable errors, or just spit general errors back to the user:

if(!database_exists()) s_error("Our database has been stolen!",true,1,true);

if(!is_friendly($_POST['username'])) s_error("Sorry, you're mean!");

LordShryku
07-15-2004, 03:00 AM
Alright, I've answered this question so many times now...

Q: I have a form with a textarea. When the user submits the form, the multiple lines from the textarea are all on one line. Why?

A: nl2br! You have to convert the new line characters from the textarea fields to HTML break tags.

Merve
07-15-2004, 11:32 AM
Too add to LShryku's comment, an answer to another common question: "Why are there backslashes all over the place?"

Use stripslashes

Bunkermaster
07-15-2004, 11:37 AM
http://www.phpbuilder.com/board/showthread.php?s=&postid=10322030#post10322030

added to FAQ

suepahfly
10-19-2004, 05:11 PM
As someone mentioned somwere on this forum;
Use print(); for debugging and ECHO for normal output.

This way you can easily find them in your code.


if(false !== $foo))
echo $bar;

print($foo .' '.$bar);

Bunkermaster
11-23-2004, 10:18 PM
hmmm i for one like to have my code clean
<?
define( 'DEBUG' , 1 );
if ( DEBUG ){
echo "something";
}
?>
I use this to display SQL from queries and time them (ALL OF THEM) for optimization and such niceties.

Shrike
03-20-2005, 07:34 AM
I sometimes put a die() statement after a debug statement, that way you often won't end up with a page of HTML masking your debug lines.

Test your code in bitesize pieces, that is don't write an entire script and then debug it, write a function or a method and then debug it with dummy data.

This leads naturally on to Unit Testing (http://phpunit.sourceforge.net/).

Finally Comment Your Code! I am the worst offender for not doing this and it has often led to hours of confusion about why something does something.

tekky
03-20-2005, 09:11 AM
Just to simplify on a seeminlgy good idea...

functions.php
function s_error($msg='Undefined Error', $kill=false, $priority=3, $log=false)
{
//one time call to a used everytime function
if ($log === true)
log_error($msg,$priority);
switch($priority)
{
case 1: // Alert the troops
//assuming this log_error was supposed to be identical to the other 2 and removing it also
sound_the_alarms($msg);
die('We might not be back for a bit.');
case 2: // Unrecoverable system error
die('System Error: ' . $msg);
case 3: // User / general error
echo "Sorry, an error occurred: " . $msg;
break;
default: // Or however else you want to handle this by default
die('Unspecified error');
}
return false;

}



Obviously, a lot more can be done with this, like handling error codes, formatting user errors, sending messages off to your mobile, etc. I check for an array in $msg and list multiple errors through a templater for example.

This way you can handle unrecoverable errors, or just spit general errors back to the user:

if(!database_exists()) s_error("Our database has been stolen!",true,1,true);

if(!is_friendly($_POST['username'])) s_error("Sorry, you're mean!");

Drakla
06-25-2005, 10:18 PM
Originally posted by Merve
Too add to LShryku's comment, an answer to another common question: "Why are there backslashes all over the place?"

Use stripslashes
It's hot needles in the eye time when I see "You put addslashes when you put data into a database and stripslashes when you take it out"

It's become like an old wives' tale of sql programming.

toplay
08-03-2005, 06:02 AM
Check for double-equals ==

If your conditional statement isn't working properly, and it's testing for equivalence, check that you've got two equals signs.
I'm just going to expand on this and share a tip that would help if you've been using literals and constants on the right side of an 'if' expression. Example code:

$value = 2;
if ($value = 1)
echo 'one'; // This gets displayed
elseif ($value = 2)
echo 'two';

The equal comparison operator in PHP requires two equal signs (==) and not just one (=). One equal sign is an assignment operator. In the example code, the '1' was assigned to the $value variable at the first 'if' expression, and this made the expression evaluate to TRUE; causing the echo 'one' to be executed and displayed. With this type of code example, PHP produces no errors (when there's a variable name to the left of the equal sign). This makes debugging this kind of problem more difficult and potentially time consuming. It's not always very apparent.

Here's a tip to avoid this problem in the future. Get in the habit of coding the 'if' expression with the literal value or constant first or to the left of the equal sign, like this:

$value = 2;
if (1 == $value)
echo 'one';
elseif (2 == $value)
echo 'two'; // This gets displayed

That way if you happen to make a mistake and put just one equal sign again, then PHP will give you a parse error. The code of '1 = $value' is invalid because PHP can't assign the contents of $value to '1' (a literal; it must be a variable). This could potentially save you lots of time in testing/debugging because you get an error alert.

Check variable contents
Use something like this to check you received what you expected to receive


echo '<pre>';
print_r ($_POST);
echo '</pre>';

That could be done in one line:

echo '<pre>', print_r($_POST, TRUE), '</pre>';


hth.

kakki
08-12-2005, 10:44 AM
or use // */ comments in your code, to check/uncheck it

used code:

echo '<pre>';
print_r ($_POST);
echo '</pre>';
// */


unused code

/*
echo '<pre>';
print_r ($_POST);
echo '</pre>';
// */

kakki
08-12-2005, 10:46 AM
if your mysql comes up with error messages
instead of this line:

$q=mysql_query ( "SELECT * FROM table" );


do

//$q=mysql_query
echo ( "SELECT * FROM table" );


so you can see the sql directly

tekky
08-12-2005, 02:11 PM
if your mysql comes up with error messages
instead of this line:

$q=mysql_query ( "SELECT * FROM table" );


do

//$q=mysql_query
echo ( "SELECT * FROM table" );


so you can see the sql directly


not to be a hard*ss, but if i type in "SELECT * FROM table" then I have no need to echo it... maybe a better example like...


echo "SELECT $columns FROM $table $where";


would be more appropriate ;)

Plasma
02-04-2006, 06:21 AM
When working with databases, use a database object - And all queries are sent through it, eg

$db->query("SELECT * FROM $table $where");

Then, while your developing your site, you can have the db object always echo out the query being used (and runtime information that query took) to help in development.

Another tip, 'return early'.

If you can stop processing another line of code by doing a simple check, then do that. For example:

Its better to do this:

if ($data == '')
return;

Than:

if ($data != '')
{
// do stuff here
}

And having it in one big IF statement.

Weedpacket
04-01-2006, 07:52 AM
Bung Xdebug onto your server

The Xdebug (http://pecl.php.net/package/Xdebug) extension from PECL is something to go on your development server. It boosts PHP's error reporting with a lot more information about what it was doing when the fault occurred.

matto
12-01-2006, 01:06 PM
Hi all,

there have been a few suggestions in this thread regarding how to benefit from var_dump and print_r. Over the years I've come to the following dumping functions which are available in all of my PHP projects and are quite handy.

Simply spoken, "vd" means "var_dump" only that is shorter and more useful.
"vdd" means "var_dump and die" - stops execution immediatly after output.

/**
* vd functions version 1.1 by matto
*
* dump any object
* set return_it to true so the dump will be returned as a string
* otherwise it will be dumped to the screen
* html_entities filter will be applied
*
* @param mixed $anobject, boolean return_it
*/
function vd($anobject, $return_it=false)
{
ob_start();
var_dump($anobject);
$out = ob_get_contents();
ob_end_clean();

if(!$return_it)
{
echo "<pre>";
echo htmlentities($out);
echo "</pre>";
}
else
{
return htmlentities($out);
}
}

function vdd($anobject)
{
vd($anobject);
exit;
}

Everything gets nicely formatted, HTML won't be interpreted, plus you can re-route output into a variable in order to collect it for later display. Hope you find it useful.

Shrike
12-01-2006, 01:13 PM
Weedpacket mention Xdebug just above, which can also format the output of var_dump() for a browser. It also creates some process log files which can be analysed in KCacheGrind or the windows equivalent WinCacheGrind. Handy for finding code bottlenecks.

Weedpacket
12-01-2006, 11:46 PM
"var_dump and die"That reminds me; anyone else been thinking of PHP t-shirt slogans? :)

bradgrafelman
12-02-2006, 12:23 AM
Hmm... something about combing a "_dump" function and flush() ? :p

Weedpacket
03-03-2007, 09:03 PM
Cut-and-paste code does not work

As the programmer, it is your responsibility to understand what your code is doing and what it is supposed to do; the computer is not capable of doing that for you. Taking chunks of other people's code and inserting them into yours without bothering to work out how to use them is a sure way of turning your code into an unworkable mess.

If it's a class, study its interface to see what it provides and then decide if you can use it to do what you're wanting. If it's just a fragment of code of the sort that is posted here to illustrate a solution, remember that it is just an illustration and not necessarily the real thing. Who knows what it will do when you run it? If you don't, you're in trouble.

banzaimonkey
04-06-2007, 10:23 PM
Run PHP from the Command Line

Testing in a browser is handy for seeing HTML output, but a lot of other things are lost. If you run your script from the command line you can see whether or not PHP is "fixing" your code for you, particularly in the case of uninitiated variables that PHP sometimes handles on its own.

crux_op
04-11-2007, 06:14 PM
Isn't that what E_STRICT is for... to make PHP throw an error for every uninitialized variable instead of doing 'magic' and producing a value on its own?

philipolson
04-11-2007, 06:57 PM
When using (uninitialized) variables that do not exist, errors of level E_NOTICE are produced and you cannot stop the PHP voodoo magic (like making $foo[bar] turn bar into 'bar'), it happens, but to go along with the magic you can produce (and find) the errors if (when) you turn them on.

People are encouraged to log (http://php.net/manual/en/ref.errorfunc.php#ini.log-errors) all errors instead of using display_errors (http://php.net/manual/en/ref.errorfunc.php#ini.display-errors) = on but regardless the main goal here (on this specific subtopic of eliminating php errors) is to turn on ALL errors, test the code, and eliminate said errors.
error_reporting(E_ALL | E_STRICT);
http://php.net/error-reporting
http://php.net/manual/ref.errorfunc.php#e-strict
http://php.net/set-error-handler

Wow, this thread is old :-)

überfuzz
03-28-2008, 06:00 AM
I find print_r() very useful whiledebuging.

$a = /*???*/; If you're not 100% on what a variable/array contains
echo "<pre>";
print_r ($a);
echo "</pre>";

The out put will be quite understandable.

Edit: wops this hint was allready posted. Sorry!

dougal85
03-28-2008, 08:33 AM
However, as an adition to print_r you can use print_r($var, true); so rather than displaying the output it returns it as a string.

This can be then used in an error log and is often very useful.

NogDog
03-28-2008, 03:22 PM
Don't forget about debug_backtrace() and debug_print_backtrace().