<? Getting Out Of Trouble?>

Troubleshooting

Now that we are beginning to become dangerous with our code, lets review a few troubleshooting tactics. Before we get into what to do in a specific instance, let's go over a few PHP development ground rules:

  1. Always build and test your pages in small increments. Don't make large changes and expect things to go smoothly!
  2. Back up your working pages. Never risk damage to a working page when making changes.
  3. Make extensive use of documentation, both inside the code, and on a development journal, in your case, the blog.
  4. NEVER PROGRAM WHEN YOU ARE TIRED. Learn to stop typing, back away from the computer, and take a break and come back later.
  5. Note the problem you are running into, in your documentation, so you can troubleshoot later!  When you lose, don't lose the lesson.
  6. Programming takes time.  Remember the 80/50 rule?  When you think you are 80% done with an application, you are perhaps 50% done regarding time spent.  Many problems don't surface until you are near completion.

PHP Error Reporting Levels

When installed PHP by default shows all error messages. While this is a good thing while you are developing your site, it may be a bad thing in a production environment with live customers! This is because once we have made the site live, we may not want to display our lack of skill, or worse, display error messages that help a hacker determine our database structure and field names.

The level of error reporting is set in the php.ini file.  The error messages are shut on or off by the setting called "display_errors", which is set to "on" if you wish any errors to be displayed.  While there is a great amount of information on how to configure PHP to display errors by changing settings on an individual page, currently there is no way to overwrite display_errors in the current PHP.INI file, if it has been set to off!

Once you have "display_errors" set to "on", you can set the amount and type of errors set with the setting called "error_reporting". This setting accepts a number (no quotes) to indicate the type of errors that will be displayed. For development purposes, the proper setting would be 2047, which shows nearly all errors.

You can alter the error-displaying sensitivity on a particular page and control what types of errors should be reported by declaring the level of reporting with a PHP function named error_reporting():

error_reporting(E_ALL); // everything
error_reporting(E_ERROR | E_PARSE); // only major problems
error_reporting(E_ALL & ~E_NOTICE); // everything but notices

As the parameters of the function, &, | and ~ are all bitwise operators to determine what kind of errors are to be reported:

  1. | stands for ‘OR’.
  2. & stands for ‘AND’.
  3. ~ stands for ‘NOT’.
PHP Error Types

Value

Constant

Description

Catchable

1

E_ERROR

Nonrecoverable error

No

2

E_WARNING

Recoverable error

Yes

4

E_PARSE

Parser error

No

8

E_NOTICE

Possible error

Yes

16

E_CORE_ERROR

Like E_ERROR but generated by the PHP core

No

32

E_CORE_WARNING

Like E_WARNING but generated by the PHP core

No

64

E_COMPILE_ERROR

Like E_ERROR but generated by the Zend Engine

No

128

E_COMPILE_WARNING

Like E_WARNING but generated by the Zend Engine

No

256

E_USER_ERROR

Like E_ERROR but triggered by calling trigger_error( )

Yes

512

E_USER_WARNING

Like E_WARNING but triggered by calling trigger_error( )

Yes

1024

E_USER_NOTICE

Like E_NOTICE but triggered by calling trigger_error( )

Yes

2047

E_ALL

Everything except E_STRICT

N/A

2048

E_STRICT

Runtime notices in which PHP suggests changes to improve code quality (since PHP 5)

N/A

 

Catching Errors

As you view the list above, you see a column named 'catchable'.  Errors of the 'catchable' level can be responded to inside our code.  Errors that are not catchable either show an empty HTML page, notable for placing upper case <HTML> tags (and not much else) in the source when error reporting is turned off, or display an ugly white page describing the page that created the error, the type of error as determined by PHP, and the line of code where the error occurred.  This is a goldmine for hackers, so it is no surprise that in a 'production' website (one in use by customers) error reporting is so frequently turned off. 

PHP Error Messages

While we are working, we want error reporting set in such a way that whe we have errors in the code, PHP will attempt to report them to you. The first type of error we get are called parse errors (E_PARSE). Parse errors are usually simple typos, like forgetting to add a dollar sign to a variable, or close a quote, or end a line with a semi-colon. PHP will report the type of error, and attempt to give you the line number on which it appears. Note that on this error, and others the line number is the general vicinity of the error, in practice it may be close, but not exactly the line number indicated! Here is an example error:

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /home/classes/horsey01/public_html/error.php on line 2

In this case the offending code was on line 2:

prnt "blah";

Here we created a typo by leaving the letter "i" out of the print command.  Note that PHP does not know exactly what has happened, and when it sees a command it doesn't recognize, it misjudges the command to be a constant, which is like a variable that doesn't vary (doesn't change) but is recognizable by not having a dollar sign.  Here's another example:

Error messages will be reported one at a time, starting with the parse errors. As you fix the errors, more may be reported. This means you are making progress! Another type of error can be called the expected error. This error frequently occurs when PHP expects to see something, but doesn't get what it expects. PHP will tell you "expected }" and give the line number, for example. This is difficult to troubleshoot, as the line number is FREQUENTLY unrelated, in this case. This is because you may have a curly brace turned the wrong way, for example. PHP looks for the match to an open brace, and when it doesn't find it, it keeps going down the page, sometimes to the bottom, before reporting the error! Here's an example:

Parse error: syntax error, unexpected $end in /home/classes/horsey01/public_html/error.php on line 7

In this case the offending code was on line 4:

include "asdf

Since the command was unfinished, PHP continued down the page, and indicated the page came to an unexpected end (unexpected $end above) on line 7, the last line of code! 

Error Suppression

Historically we could 'supress' error messages on a line by line basis by placing the "@" symbol in front of our potentially offending code:

@include "my_inc.php";

This appears to work less often, and on less servers.  Further, it hides errors we may wish to fix.

or die() Function

PHP being a determined language, uses an odd construct, and displays a functional kind of a 'do or die()' attitude in some of it's code.  View the following example:

mysqli_query($iConn,$sql) or die(print mysqli_error($iConn));

Although this example is a little beyond us as it represents a connection to the database, notice the highlighted or die() section of code.  If PHP encounters an error connecting to the database to retrieve data, we can optionally place code to be run if an error occurs.  In this case we print the database error to the page, and stop the page from running entirely.

Print and Die

Sometimes you make a mistake inside the code that is not visible when the page is run. We may wish to halt page execution, and print data to the screen, so we can see what is going in our page. To do this, we do what is called print and die.

print "myVar: " . $myVar;
die();

The above example prints a variable to the page and halts execution. No code is run beyond the "die" statement. The die() works identically to the exit command.  You can print the contents of any number of variables just before the die statement, to see what the current contents include. You can check your pages in various locations in this manner.

Another version of the above uses print_r() to allow us to print the value of an array, without a loop:

print_r($myArray);
die();

A more comprehensive trick is to use var_dump(), which prints information about a series of variables, arrays or objects etc:

$b = 3.1;
$c = true;
var_dump($b, $c);

Other Tips

Another trick is to comment out possible offending code, to narrow down where the mistake can be. Remember to use the larger scale comment tags, /* and */ for this.

HTML Output: Sometimes you will need to view the output of the page, after the page is run. If you have an HTML error, like a missing quote, the HTML could submerge, or no longer be visible, but could show up in the output of your PHP page, when the source is viewed in a browser.  If your problem is an HTML problem instead of a PHP problem, you can copy all pertinent HTML and work in Dreamweaver (for example) to troubleshoot the HTML problem.

Seeing No Changes?: Lastly, if you are making changes to your page, and nothing makes a difference , add a print and die line at the top of the page, and see if the message appears. If it does not, you may be uploading to the wrong directory, or the FTP client may not be updating the page, which CAN HAPPEN with Unix!

At this point you could rename your page and save it elsewhere to see if you can see your page changes. STOP MAKING CHANGES the moment you suspect nothing is working! If you continue making changes, you may be compounding the problem!

Error At The Bottom Of The Page?: If you see an error message, and the code points to the last line of a PHP block, the usual cause is a curly brace or paren turned the wrong direction.  If you open another curly brace, instead of closing it, PHP looks for the match until it hits the end of the block.  If no match is found, an error is reported.

Case Sensitivity: PHP is strangely inconsistent on case sensitivity.  It is OVERLY case sensitive on variables you create.  It also is case sensitive on SuperGlobals, such as $_POST and $_SERVER.  However, on it's own functions, such as phpInfo(), it is not case sensitive.  When PHP encounters something that is in the wrong case, it will not know what you wanted.

Fun With Quotes: While you can use double or single quotes in print statements, remember you must stick with one per statement.  You can also get into trouble when you need to escape the type of quotes you are using.  Later, single quotes will trip up MySQL.

Assignment vs Comparison: Assigning a variable uses a single equal sign, but to compare a value, we use a double equal:

if($a == $b)
{

    print "they are equal!";
}

If you mix these up, you get unexpected results!  Also remember your compound operators, like += can have no space between the characters!

Exceptions

For more advanced error handling, starting with PHP5, we can move away from the or die() function and  use an exception model similar to other programming languages.

We can use a try/catch block to determine if our program will crash, or even if we are getting data we did not expect.

For examples, view Exceptions in PHP

Performance Warning: Only use exceptions in exceptional circumstances!  And that is across all languages: Try/Catch Performance

Print this Page Back To Top

© 2000- 2010 newMANIC INC, All rights reserved