Squash Those (Programming) Bugs!
As any programmer knows, the bane of our existence is an error (or lack of an error in some cases) that we can’t seem to track down. Here’s 3 quick debugging tips to help you become a more efficient programmer.
1. Turn on all error reporting
One of the easiest fixes is to make sure all errors being thrown are being displayed. There are two settings in PHP that you can change to make sure all error information is being displayed. Place the following two lines of code in your PHP file to turn on all error reporting:
- ini_set(‘display_errors’, ‘1’);
You can either add the above code to your PHP file or alternatively, you can set the same value (display_errors) in your .htaccess or php.ini file.
E_ALL refers to all errors, even notices. If you aren’t concerned with fixing any notices, you can use display_errors(E_ALL ^ E_NOTICE);, which will not display notices.
Once you know the error, PHP should point you towards the offending line of code. But, in some cases, you’ll have to use other methods…
2. Line By Line
Sometimes PHP doesn’t throw an error at all and just leaves you with a blank screen. In this case, you can either read through the code line by line or start dissecting your script into chunks. For example, if your script is 100 lines long, you can place die(); statements every 25 lines to figure out how far it’s getting in the script. Once you figure out which section is causing problems, you can further dissect that section into smaller subsections, until you narrow it down to a few lines of code.
3. Missing Semi-Colon
One of the most common issues I run across is a missing semi-colon at the end of my lines of code. You don’t want to be scouring through things line by line, so I use a simple little regular expression search to try and pin point any lines that don’t end in a semi-colon. By simply searching for [^t;]n (which translates to search for any character that isn’t a semi-colon, followed by the newline character) it highlights which lines may be causing my script not to run.
In the brief example below, it highlights lines that may not necesarrily be causing problems, but it does help highlight any lines that may be the culprit.