If you have ever written your own scripts in PHP or another programming language, you know the frustration that comes from debugging your work.
Write an HTML page and leave off a closing </table> tag, or even something vital like the <body> tag, and most of the browsers in use today will display the page as you intended, even with the errors. But programming languages in general – and PHP specifically – are not nearly as forgiving; leaving off even a single semi-colon can stop the execution of the entire script.
In this article, you’ll learn more about programming errors and the types of core error handling features PHP offers. You’ll also learn a few tips and tricks for troubleshooting common errors in your own scripts.
Types of Errors
Generally speaking, there are two types of errors in programming: Syntax Errors and Logical Errors.
A syntax error is a lot like a grammatical error in a sentence; something that you have written (or omitted) has broken the rules of the language. Common mistakes such as missing semi-colons, mismatched or un-escaped quotes are all good examples. Because a statement is either formed correctly or incorrectly, syntax errors are objective, and the easiest to troubleshoot.
Logical errors, on the other hand, are far more insidious. These occur when the flow of the application has been incorrectly conceived or programmed. It is easy to see when one exists because the script does not produce the desired results, but hard to isolate and fix because no error messages are produced (at least not directly).
Preventing and Resolving Errors
Prevention of logical errors should begin before a single line of code is written, especially on larger projects that have more contingent programming. By outlining each of your scripts using pseudo code, much like you might outline a speech or essay you were planning to write, you can develop a framework to follow when you begin scripting.
For example, if you were writing a script that accepts input from a user in a form and then emails the information, the pseudo code might look something like this:
If the form has been submitted, then Check to see if all the fields are filled out. If they are, then Email the form contents Display a thank you page Exit the script If they aren’t Create an error message Display the form |
As you can see, though written in such a way that even a layman could follow, this pseudo code bares strong resemblance to a standard PHP if statement.
Because a framework like this addresses all the logical aspects of the script’s program flow in advance, following it during the programming process helps you stay on track and naturally minimizes logical errors. When you become more familiar with the logical apsects of programming, you can rely less on an outline process in advance. For large projects, it typically becomes necessary only to outline which scripts you plan to write, and what their functions should be.
Unlike logical errors, syntax errors seem to stubbornly defy prevention, even for the most experienced programmer. They pop up as typos, misnamed variables and accidental omissions. The trick to handling them is being able to quickly isolate and fix them. Generally, this is easy to do because PHP terminates with an error message citing the line number and type of error; most times it’s just a matter of knowing what to look for. Below are a few common PHP error messages:
General Parse Errors
Examples: Parse error: parse error, unexpected T_… in /home/httpd/www/index.php on line 3 Parse error: parse error, unexpected T_… in /home/httpd/www/index.php on line 4 |
Parse errors usually offer little clue to the exact problem (although error messages in the latest versions of PHP are becoming more specific), but do give you the correct line number to look at most times. Check for missing semi-colons, quotes and parentheses as well as mismatched quotes on the line specified in the error, as well as those directly before it.
If the parse error message references the last line of the file or a line where there is no PHP, it usually means that you have forgotten a closing bracket ( }) on a loop or if-else statement.
Header Errors
Example: Warning: Cannot send . – headers already sent (output started at /home/httpd/www/index.php:2) in /home/httpd/www/index.php on line 5 |
This type of error occurs when you attempt to send header information after you have already outputted information to the browser through PHP or with HTML. This applies not only to the header() function, but also to cookie and session functions.
Paremeter Count Errors (functions)
Example: Warning: Wrong parameter count for explode() in /home/httpd/www/index.php on line 5 |
Unless specifically set up to accept a variable number of arguments, functions in PHP require that the number of arguments being passed to them match the number specificed in the function declaration. Especially in PHP’s pre-defined functions, be sure that you have not left off or added an additional argument.
PHP’s Error Handling Features
In the development phase of creating an application, having notices and errors displayed in the browser is vital. When the project is live, though, displaying errors to users is frequently undesirable, especially since error messages can contain run-time information about the server and script. Depending on what it is, this information can be a boon to potential hackers. This is just one of the reasons that PHP provides flexible options for controlling when, how, and which errors messages are displayed.
As you may have noticed from the sample error messages in the previous section, PHP divides syntax errors into three separate groups: Parse Errors, Notices and Warnings. Parse Errors are classified irrecoverable errors which stop the execution of the script, while Notices and Warnings are less serious and do not stop the script.
To allow the internal settings and functions to control how errors are reported, PHP assigns constants and values to each of the various types of errrors. The following have been available since PHP3:
|
And these were added in PHP4:
|
The PHP.ini is the primary location for controlling error reporting options and contains several settings to manage them; including error_reporting, display_errors, and error_log.
The first, error_reporting, uses the constants listed above, and several logical operators (“|”,”~”, “!” and “&”) to build up an expression describing which errors should be displayed. For example, the default setting in PHP4 is: E_ALL & ~E_NOTICE. This indicates that all error messages should be shown, except for notices.
When set to “off”, the display_errors suppresses all Parse Errors, Warnings, and Notices that would normally be sent to the browser. This setting works in conjunction with error_log, which allows you to specify that errors should be saved to the server’s error log.
Errors reporting settings can also be set on a script-by-script basis using the error_reporting() function. The rules defined by this function are only in affect for as long as the script runs. This is especially useful in situations where you may want to display errors in a particular script for development and debugging, but suppress them once the script is ready to go live without making global changes in your PHP.ini. error_reporting() accepts constant names (the encouraged method) in combination, as in the PHP.ini, as well as their integer values:
error_reporting(0); – turns off all error reporting. error_reporting(E_ALL); – turns on all error reporting. error_reporting(E_ERROR | E_WARNING); – shows critical errors and warnings only. |
You can also suppress errors generated by a particular expression within a script by including the proceeding it with the @ symbol. For example: @unlink($file);
Keep in mind that even if you supress errors through any of the above methods, a script will still stop executing should the PHP processor encounter a critical error.
A Note on Creating Your Own Error Messages
You may have noticed that some of the error constants in the previous section referred to user created errors. Though beyond the scope of this article (and the needs of most new PHP programmers), keep in mind that PHP also provides advanced functions which allow you to create and impliment your own error messages. For simple scripts the need to add custom error handling is questionable, but in full-fledged applications the benefits become more apparent. By creating your own error handling functions, you can control the output; for example, you could provide contact information for the adminstrator of the server, or redirect the user to another location. You could also send out an email to notify you if a critical error had occured.
The set_error_handler() function allows you to build in this functionability to your own scripts.
Finally
Hopefully, this article has armed you with the knowledge to intelligently manage and combat errors in your own scripts. Avoiding, and understanding how to quickly troubleshoot errors in your work will greatly decrease the time it takes to get a script from the development phase to afinished product.
In the next article, we will be taking a look at some more theory of programming with PHP, covering aspects of coding style.
Stay Tuned!
Things to remember:
|
Liz Fulghum currently lives in Annapolis, MD where she works as a web designer for a custom shirt retailer. Liz was convinced to try PHP as an alternative to Perl; she has been a fan ever since and frequently works as a freelance developer.
# # #