FireworksColdFusionDreamweaverFreehandFlashMXHome
Latest New Content

Latest Free Content
View All
Free Content
Accessibility
CMX Learning Guides
Hosted by enterhost

PHP Phreakout: Troubleshooting Tips for PHP Code

By: Steven Seiller

Troubleshooting Tips for PHP Code

So what happens when your PHP code doesn't work as expected? What do those error messages mean? Sometimes confusing, sometimes cryptic, those little blurbs declaring that you goofed can actually be helpful! In this article, I will describe the process and some tricks I use to troubleshoot my PHP code during initial development.

For the handling of PHP errors after implementation on a web site, see Tom Muck's article entitled A Simple Error Handling Function for PHP.

How do we know when we have a problem?

I call it the "White Screen of Oblivion." You've seen it. You just finished your new code and you eagerly upload it to the server to watch the magic you just conjured. You load the script and wait. And wait. That white, blank screen opens like a void and sucks your confidence while it quickly sinks in that you have a problem. Ok, but what problem? Not even an error message?

With experiences like that, we can actually be happy when we do receive an error message—even one which says fatal. At least an error message gives us a line number and some kind of a clue!

Sometimes we get an unexpected result. Sometimes we get no result, which is definitely not the result we were planning to receive. All of these scenarios provide us with problems to troubleshoot.

What kinds of problems do we need to solve?

Before we can get into solving problems, we need to look at what constitutes a PHP code problem. Knowing the nature of the problem will help us apply a specific strategy. There are essentially four types of errors:

  1. Syntax errors can occur when your code does not meet the grammatical requirements of PHP. A common example is forgetting to include a ";" at the end of a statement.
  2. Semantic errors can occur when your code does not use basic building blocks according PHP standards. A semantic error will occur, for example, when you pass supply an array to a function which expects a string.
  3. Environment errors can occur when you do not have all the components expected to perform your planned actions. Forgetting to upload an included file will result in an environment error.
  4. Logic errors occur when your code technically works but does not give you the result you expected. When your code works with the wrong variable you will see a confusing result. Or worse, no result which is actually the logical result of your illogical instructions.

Problem Solving Strategies

Cancer Support - I'll start with the White Screen of Oblivion. The reason for the white screen is that there is such mangled code that the PHP interpreter crashes and hence no error message. If I don't have a feeling about what caused the problem, I'll take a surgeon's approach to cutting out the cancerous code. I cut half the code and upload the file again. If the script still does not run, then I can assume the problem is in the other half of the code. I undo the cut to replace the code and cut the other half. When the script runs, I know I have removed the offending code but still need to identify it. I then progressively cut less and less of the code from the script to narrow in on the problem.

Beware Gremlins! - PHP code may itself only include ASCII characters, but sometimes non-ASCII characters can steal into your code. Ever copy and paste content into your scripts from a Word document or web page? Chances are that you are pasting invisible, non-ASCII characters into your script which can be show-stoppers. Microsoft Word (or any other editor which is capable of Rich Text formatting) uses invisible codes to apply styles to text and symbols. If these characters don't stop the show altogether, you'll see them as weird, accented characters in your output. Word processors tend to use fancy, typographer quote marks (“”) but we must use straight quotes ("" or '').

My PHP coding editor of choice is BBEdit for Mac OS X which contains a search and destroy function called "Zap Gremlins" handling this situation deftly. This function is also available in their free version called TextWrangler. In your text editor, look for a function which shows control characters or non-printing characters. If your text editor does not have this feature you can sanitize your text by saving it in a text-only file format and using it from there.

Display errors and other diagnostics - Tell PHP to show you error messages and other warnings with the error_reporting directive. During development, I place the following directives at the top of my PHP script:

error_reporting(E_ALL);
ini_set ('display_errors', '1');

The first directive tells PHP to report all errors, warnings and notices. The second directive tells PHP to show these on the screen. This is useful for debugging code in the development phase, but probably not something you want your users to see when the script is in production use. After development, I typically remove or comment out these two lines so users are not subject to low-level geek messages which can be confusing or compromise server security. The errors displayed by this directive:

  1. Fatal Errors are definite show stoppers. These will typically show you syntax and environment errors.
  2. Parse errors prevent the script from being parsed and executed. These also typically show you syntax and environment errors.
  3. Warnings of non-fatal errors are shown when the problem does not prevent the script from being parsed and executed but will likely cause a problem. Warnings typically reflect semantic errors.
  4. Notices are not necessarily errors but something that could reflect a problem with syntax, semantics or logic. Typical examples include using a variable for comparison before the variable's value has been set or when the notation of a variable provides ambiguity regarding its status as a string or as an array.

Remember when I said that receiving an error message can be helpful? These messages will provide you with the nature of the error and possibly the exact location. Study these messages as they will tell you what to do. If you do not know what the error message means, look it up in the PHP documentation web site. The cause and cure of most messages are explained in the documentation and or in the comments which can be found at the bottom of each PHP Manual page. You can also do a search on the Internet which can often yield a copious collection of web sites and solutions focused on your issue.

Sometimes the error message is confusing because the problem doesn't specifically reveal itself until it causes a problem elsewhere. Typical examples include forgetting the ";" at the end of the line or not closing a quoted string. Before executing the script, the PHP interpreter will parse it by running through the code and recognizing all the instructions. Because a semicolon or quote will terminate a specific instruction, the interpreter won't discover that you forgot the terminator until it gets to the next instruction which is where it will pronounce the error. Here are some specific examples for you to see. See if you can spot the error.

53 //-----------------TESTING-----------------//
54 if (isset($_COOKIE["oldPage"])) {
55   echo "Old Page " . $_COOKIE["oldPage"] . "!<br />;
56 }
57 echo "<pre>";
58 var_dump(get_defined_vars());
59 echo "</pre>";
60 //-----------------TESTING-----------------//

Result:

Parse error: syntax error, unexpected '>' in /home/site/public_html/test.php on line 57

I forgot the last " at the end of line 55, but a problem was not discovered until near the end of line 57. You'll drive yourself crazy if you try to figure out why the '>' problem when it is not really the problem! Another displaced error:

53 //-----------------TESTING-----------------//
54 if (isset($_COOKIE["oldPage"])) {
55   echo "Old Page " . $_COOKIE["oldPage"] . "!<br />";
56 }
57 echo "<pre>";
58 var_dump(get_defined_vars())
59 echo "</pre>";
60 //-----------------TESTING-----------------//

Result:

Parse error: syntax error, unexpected T_ECHO in /home/site/public_html/test.php on line 59

I forgot the last ; at the end of line 58, but a problem was not discovered until line 59. Spotting these deceptive errors and identifying their true cause will come with experience.

Warning: Equally confusing is when you receive an error at a specific line number that is greater than the total number of lines in your script. How can this happen? When you include other files in your script, PHP will also parse those files at runtime inflating the total line count of your script. To determine the exact location of the problem either refer to the content of the message you received or see the assert() method below to leave yourself some breadcrumbs.

Spell Checker for PHP - The best way to deal with syntax problems is to prevent them! Before trying your PHP code, use a syntax checker to ensure it conforms to PHP standards for grammar and punctuation. PHP has a built-in syntax checker which scans your file for parse errors. To use this feature, you need to feed the following to the command line:

php -l /path/to/your/file.php

If you are not comfortable with the command line or don't have access to it on your web server, there are some other options. I use a process described by John Gruber on my Mac which uses Applescript to submit my BBEdit file to the command line and report the results.


Figure 1 PHP Syntax check Error Message

Other editors offer this feature, but I have not found such a solution for Dreamweaver. You might try a web site which offers this function as a free service.

Logical Error: An Oxymoron? - Logical errors can be difficult to troubleshoot since you will typically not receive a specific error. Logic errors occur when your code doesn't fail from technical problems but does not give you the result you expected. Many times, the result you get is no result at all which gives even less to work with.

In my experience, I create logic errors when I:

Breadcrumbs To Sanity - The way I track down logic problems is to backtrack through my code to confirm the result I am expecting is the result that I am receiving. This I do primarily by displaying on screen the contents of variables and the results of operations not normally shown. To use these methods, I insert them as needed in the flow of the code and run the script to see the output. Once I have solved the problem, I removed the testing code from the script to clean up the output. The following are functions I use for this purpose of testing.

echo - Echo the value of the variable on-screen to verify its value. I echo the name of the variable with its value to not only make clear which variable is being outputted, but also to mark the spot of output in case there is no value to show. If I didn't print the name of the value, nothing might be printed which does not help clarify the process.

//-----------------TESTING-----------------//
echo "myVar: " . $myVar . "<br>\n";
//-----------------TESTING-----------------//

Result:

myVar: 18

print_r() - Print_r shows the value of a variable in a human readable format. This function is particularly useful for arrays. Note the use of the <pre> tags when ensures that your web browser will keep the output readable. This method is especially handy for verifying the data returned by your web form which would check the $_POST array.

//-----------------TESTING-----------------//
echo "<pre>";
print_r ($myArray);
echo "</pre>";
//-----------------TESTING-----------------//

Result:

Array
(
  [a] => apple
  [b] => banana
  [c] => Array
  (
    [0] => x
    [1] => y
    [2] => z
  )
)

var_dump() - For more complex scripts which manage a lot of environmental data, you can use the var_dump() function to print all defined variables. Be forewarned that you will likely receive dozens of screens full of data, but if you are looking for that proverbial needle in the hay stack this is the equivalent of using a leaf blower! If you are just learning PHP to use as a Common Gateway Interface (CGI), the output of this function will show you an amazing amount of resources at your disposal.

//-----------------TESTING-----------------//
echo "<pre>";
var_dump(get_defined_vars());
echo "</pre>";
//-----------------TESTING-----------------//

assert() - Sometimes when you don't get the result you are expecting it is difficult to tell if a control structure has been processed as expected resulting in the non-response or if it didn't process properly resulting in the unexpected result. The assert() function will show a warning when the statement being asserted is false. I think of this function as a checkpoint in the PHP code flow.

56 //-----------------TESTING-----------------//
57 assert(false);
58 //-----------------TESTING-----------------//

Result:

Warning: assert(): Assertion failed in /home/site/public_html/test.php on line 57

The usefulness of this function is shown in the following exercise.

15 $action = "Save";
  ...
33 if ($action = "Lookup") {
34   // Start database lookup procedure...
35   echo "Loading..."
36   ...
37 } else {
38   // $action = Save so start database Save procedure...
39   assert(false);
40   ...

Result:

  Loading...

In this example, even though I verified the $action variable is set to "Save" before line 33, the save process starting on line 40 is not happening. To confirm whether the problem was with my database save procedure I included the assert function at line 39. What is supposed to happen is that once the script sees on line 37 that the $action variable is set to "Save", it will display the assert warning. The warning did not appear.

Quick Quiz: Do you know why the assert warning did not appear? Go to the article support forum using the link at the conclusion of this article. Earn a gold start by submitting your guess on the error.

Other Suggestions

Conclusion

All of the above methods for troubleshooting PHP code have proven themselves to me as valuable diagnostic tools. Even though I have been regularly practicing PHP coding techniques since 2002, I still make typos, logic errors and forget to upload included files. Over these years, I have also practiced troubleshooting problems with code. It gets easier with experience and I use these same practices when I assist others with their code problems. I encourage you to develop your own toolbox for problem solving and hope these tools be of good use for you.


Keywords
PHP, Code, Coding, Error, Troubleshooting, Fatal, Notice, Warning, Parse, Syntax, Semantic, Environment, Logic