
THE DEBUG FLAG
When PHP scripts don’t work as expected (and that happens quite often, right?) it’s a common practice to “debug” them changing some variables and putting some echo here and there.
If you don’t want to set up a proper debug environment (or if it’s not possible), you can just change some code to see how the script works under certain conditions.
You can force the value of variables containing data from the request string (like the $_REQUEST global array) or from a database, and you can also change some of the script logic for debugging purposes.
For example, when debugging PHP daemons I usually change the iteration interval, setting it to a very small number so that the script iterates immediately.
During these debugging sessions you can easily end up with a lot of changes, all of which must be removed at the end. The risk, of course, is that some of these changes are left there by mistake and end up in the production environment.
It happened to me (more than once, I admit…). Last time I was testing a script and I changed a timestamp value.
I totally forgot about that when I put the script back in operation, and the next day I spent a lot of time trying to understand why the script wasn’t working as expected…
One solution to this problem, which I used at the beginning, is to add a comment near every change, something like: /* debug change here */.
When you’re done debugging, you can search for all the comments and undo all the changes.
However, it’s easy to forget to add all the comments, and sometimes you can also forget what is that you changed exactly in the code.
A better solution, that is both easier and safer, is to use a Debug Flag.
You need to declare a “flag” at the beginning of the script (or where you think it’s most appropriate) that will be used to set the script into debug mode.
For example, you can declare a constant called DEBUG and set it to TRUE when you want to debug the script.
Then, instead of changing the script code, you need to use if statements to conditionally execute the debug changes only when the debug flag is set to TRUE.
The following example clearly shows how it’s done:
<?php
const DEBUG = TRUE;
$birth_year = intval($_REQUEST['birth_year'], 10);
/* Debug condition */
if (DEBUG)
{
$birth_year = 1983;
}
$y = intval(date('Y'), 10);
$age = $y - $birth_year;
echo 'You have ' . strval($age) . ' years!';
This way, when your debug session is finished, you only need to remember to switch the debug flag back to FALSE, without worrying about searching for all the changes you made and, more importantly, without the risk of leaving some of those changes in the production environment.
If you have any questions, feel free to ask in the comments below or on my Facebook Group: Alex PHP café.
If this tip has been helpful to you, please spend a second of your time and share it using the buttons below… thanks!
Alex