Saturday, May 30, 2009

Elusive PHP syntax errors - a strange fix.

I found a variety of syntax errors when debugging a PHP script lately. Since the PHP parser isn't the clearest when it comes to debugging (and these were terribly elusive) here are are some methods that I found to solve the problem.

The line numbers associated with the errors were no help at all - the error just wasn't found on line 1. And then when the line number changed, it was not found on line 34 either.

These errors included both "Unexpected $end" and "Unexpected [T_variable]" errors.

As this script was a mixture of PHP and HTML, the page was fairly long and daunting. I looked for missing brackets, tick marks, quotes, and reserved words.

I reviewed every line of code for semicolons and matching parentheses and brackets. No luck. I tweaked variable names in the lines above where the reported error was. Still no luck. Since from what I've read about debugging PHP syntax errors said the line number is 'around' or typically a line or two above the reported line number, I sat there staring at each place the bad formatting of code should have been. Nothing!

One method I came up with that I didn't find online was to separate the script into chunks. As it was a syntax error (how things were formatted), I simply segmented the script as I could, added a little HTML 'hello world' to the page (to make sure I wasn't just seeing the PHP white screen of death), and previewed different sections of the code up on the server.

I copied each logical segment of code to a new file and ran it. No errors. Eventually I copied the entire contents. Still no error in the new file. At that point I was about to pop in frustration.

I was methodical and the fact that the errors changed when I tweaked code in the original file (which seemed formatted correctly to me to begin with), was annoying to say the least.

It could be that there was a small part of the file which was corrupted while I had it open in notepad++ or maybe up on the server. Strangely enough, copying the entire contents of the script to a new file and then saving it over the old one did the trick.

It ran beautifully after that.

So, a few PHP syntax debugging tips for myself to remember in the future. Especially if they become elusive and persistent like this last time.

1.) Use something like Notepad++ to help highlight matching brackets, reserved words, quotes, and semicolons.
2.) See the PHP Syntax error wiki.
3.) If it's a long script and the syntax errors jump to different line numbers after tweaks, first copy the entire contents to another file then take segments of the code and paste it into a new file.

0 Comments:

Post a Comment

<< Home