Beginners’ Corner: Avoid Bad Habits
July 7, 2008 8:03 pm Beginners' Corner, PHPThis is the first "Beginners' Corner" article, designed to help new PHP programmers in their quest to become veteran PHP programmers. In this initial installment we'll look at a few things which are best avoided, but for various reasons often become habits of new PHP users who do not yet know better. Many of these may become habits simply because there are so many bad examples out there to learn from, often because they are dated and PHP has moved on in a manner which obsoletes them.
<?php Tags
The first bad habit to avoid is using <? instead of <?php or <?= instead of <?php echo. While saving those few keystrokes is a temptation to all of us lazy programmers, it is a potential problem should you need to run the script on a site where the short_open_tag option is disabled. One likely reason to have it disabled is in order to avoid confusion with <?xml tags in XML documents, and as XML is much more prevalent now than it was when PHP was created, you are more likely to find such configurations in use; so just get in the habit of typing those three extra characters and saving yourself a lot of aggravation in the future.
Eschew register_globals
The register_globals configuration option, when turned on, populates a set of variables in your script from any post, get, cookie, and/or session data. This is often seen as a convenience, providing you with simple variables such as $name instead of having to reference it via the applicable super-global array, such as $_POST['name']. The problem with register_globals is that it can cause bugs and potentially even security risks in certain situations (generally involving sloppy coding). As a result, all recent versions of PHP have it turned off by default, and it will not even be available in PHP6. Therefore, to keep your scripts portable and forward-compatible, it is to your benefit to turn it off if possible, and always code assuming that it will be turned off.
One additional benefit of using the super-global arrays is that it makes it immediately obvious in your source code what the source is of each such variable. If you just see the $user_name variable, you cannot tell by its name whether it is a form variable, a session variable, or an explicitly set variable to hold a database query result column value. But if the variable is instead $_POST['user_name'], you immediately know that it is intended to be a value from a form using the post method.
Use the Newer Super-Globals
There are many scripts out there that still use the old $HTTP_*_VARS arrays (e.g. $HTTP_POST_VARS). As they have been deprecated for some time now and, just like register_globals, will not be available at all in PHP6, make sure you are using the so-called "Superglobals" in your scripts, instead.
