| [ Team LiB ] |
|
28.5 Debugging StrategiesThere are times when code produces unexpected results. Examining the code reveals nothing. In this case the best thing to do is some in-line debugging. PHP scripts generate HTML to be interpreted by a browser, and HTML has a comment tag. Therefore, it is a simple matter to write PHP code that reports diagnostic information inside HTML comments. This allows you to put diagnostic information into an application without affecting its operation. Often I create database queries dynamically, based on user input. A stray character or invalid user input can cause the query to return an error. Sometimes I print the query itself. I also print the results of the error functions, such as mysql_error. The same applies to code unrelated to databases. Printing diagnostic information, even if it is as simple as saying "got here," can help. Chapter 9 describes many debugging-related functions. The print_r function can be particularly helpful. You can go a long way toward finding bugs in your applications by turning on all errors, warnings, and notices. Warnings and notices may not halt your scripts, but they can indicate potential problems. Consider how PHP allows the use of a variable before initializing it. If you mistype the name of a variable, PHP creates a new variable with an empty value. PHP generates a notice if you use the value of a variable before initializing it. It may be easiest to turn on notices inside php.ini, assuming the Web server is dedicated to development. A production server should not display error messages as a security precaution. You can always turn on full error reporting from within your script with the error_reporting function. If you don't wish to disturb the HTML output of your scripts, you can write messages to a log file. The error_log and syslog functions are two solutions built into PHP. Of course, you can always open a text file in your code and write diagnostic information. If you use Apache, you can also use the apache_note function to pass debugging information up to the Apache process where it may be included in Apache's logs. Refer to the Apache documentation to learn how to create custom logs. Finally, there are several tools available for debugging PHP scripts. Zend Studio, for example, includes a remote debugger that allows you to step over each line of your script. |
| [ Team LiB ] |
|