Good Practices in PHP

Here are a few tips for those of you who’d like to write good code in PHP:

Set up a Development Server

Set up a development server or sandbox. Don’t write, test, or develop code on a production server. If you are a *nix user, you probably already have a LAMP environment on your own computer. If you are a Windows user, try XAMPP or WAMPSERVER (personal favorite). If you are on mac, try MAMP.

As you develop your PHP, you will need to be learning about the environment which it runs in, and the settings that will affect your code and/or application. This is a journey, so don’t expect to master it all at once. You will get into things like virtual hosts, .htaccess files, rewrite rules, and file permissions.

Turn on Error Reporting

At least, on your development server. On your production site, turn off displaying errors, but have them sent to a file. Check this file periodically as it will show you what unexpected things are happening in your code.

Do’s and Don’t’s

Don’t use short codes. They take longer to type, but PHP will be moving away from them in future versions. Also, the <? syntax can be mistaken for XML. Examples of short codes include <? instead of <?php, and also the syntax <?= $var ?> which is the easy way of writing <?php echo $var; ?>

Do use comments and document your code.

Don’t use a closing ?> at the end of your PHP files. Just leave it off – it is not required and it keeps you from accidentally having white space under your closing ?> so that headers, sessions, and cookies don’t get messed up.

Do use the latest version of PHP possible for developing applications. Right now the most common version / latest stable version of PHP is 5.2.8. While 5.3.x is out, there were some major changes many hosting companies and server admins have not completely adapted to, yet. Some of these deal with symlinks / softlinks / junctions and how the code is parsed. So, always try and use the latest commonly-adopted version.

Do use a versioning software of some sort (SVN, CVS, or GIT)

Related Posts:

This entry was posted in Tech Opinion, Tech Tips, Web Development and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *