PHP Best Practices

PHP is the most widely-used language for programming on the web. Here are fourteen best practices that every programmer should know and code according to this guidelines.

1. Turn on Error Reporting for development

Error reporting is a very handy function in PHP. By enable it, you might spotted the problem earlier in your code. There are several different level of error reporting; however, by enabling E_ALL can notice most errors, critical and warnings.

A very important notice, once your code is ready for production, you should turn off error reporting. Otherwise, the potential problems would be visible to all visitors.

2. Apply DRY Approach

DRY stands for Don’t Repeat Yourself. It is a very valuable programming concept. And it applied to any language, like C#,PHP,JAVA…etc. DRY approach is to ensure that you do not write redundant code. Let take an example here.

$mysql = mysql_connect('127.0.0.1', 'admin', 'admin_password');
mysql_select_db('drupal') or die("cannot select DB");

The code is not align with DRY approach.

$db_host = '127.0.0.1';
$db_user = 'admin';
$db_password = 'admin_password';
$db_database = 'drupal';
$mysql = mysql_connect($db_host, $db_user, $db_password);
mysql_select_db($db_database);

3. Indent Code and Use White Space for Readability

You should ensure that your code is readable and easy to search by indentations and white space in your code. It is because you’ll most definitely be making changes in the future.

4. Highly recommend to use <?php ?>

A lot of programmer would use the shortcuts when declaring PHP. Here are the example.

<?
    echo "Hello world";
?>
<?="Hello world"; ?>

<% echo "Hello world"; %>

To ensure further version support guarantee, it is highly recommended to stick with standard <?php ?>.

5. Always use Meaningful, Consistent Name Standard

There are two popular naming standard:

  1. camelCase: First letter of each word is capitalized, expect for the first word.
  2. underscores: Add underscore between words, like mysql_real_escape_string().

You should choice either naming conventions to do you coding.However, be consistent on your coding.

class Foo {
    public function someDummyMethod() {

    }
}

function my_procedural_function_name() {
}

6. Prevent Deep Nesting

Too many level of nesting would make code difficult to read.

function writeFileFunction() {
// ...

if (is_writable($folder)) {
    if ($fp = fopen($file_path,'w')) {

       if ($stuff = extractSomeStuff()) {
         if (fwrite($fp,$stuff)) {

         // ...
         } else {
         return false;
         }
      } else {
       return false;
     }
    } else {
     return false;
    }
  } else {
   return false;
 }
}

Obviously, the code on the above is difficult to read and understand. To enhance the readability,it is always possible to reduce the level of nesting as follow:

function writeFileFunction() {
// ...

  if (!is_writable($folder)) {
    return false;
  }
  if (!$fp = fopen($file_path,'w')) {
    return false;
  }

  if (!$stuff = extractSomeStuff()) {
    return false;
  }
  if (fwrite($fp,$stuff)) {
   // ...
  } else {
    return false;
  }
}

7. Remember to Comment, Comment & Comment

Please ensure that you leave comment inside your source code. It is very important when the project involve five to ten programmer. The comment is very important. It helps out a lot when your team have to go back and maintain a project from a long time ago.

In order to maintain a high quality of comment standard, it is highly recommened to familiarize yourself with some PHP Documentation packages like phpDocumentor, and take the extra time to do it. It’s worth it.

8. Do not put phpinfo() in your web root.

Phpinfo is a very useful function.By simple creating a PHP file that has

<?php phpinfo(); ?>

and place it to the server somewhere, you can know everything about your server environment. However, a lot of programmer would place the file contain phpinfo() in the webroot. This is a very insecure practice. It could potentially speel doom for you server. Please make sure phpinfo() is in a secure sport and delete it once you are done.

9. Never trust your user

If your application has places for user input, you should always assume that they’re going to try to input naughty code. (We’re not implying that your users are bad people. It’s just a good mindset.) A great way to keep your site hacker-free is to always initialize your variables to safeguard your site from XSS attacks. PHP.net has an example of a properly secured form with initialized variables:

 <?php
if (correct_user($_POST['user'], $_POST['password']) {
     $login = true;
}
if ($login) {
     forward_to_secure_environment();
}
?>

10. Use a cache mechanism

There are several robust caching system which are available for free. Have a look of following:

 11. Keep Functions Outside of Loops

You will suffer a hit of performance when you include functions inside of loops. The larger the loop you have, the longer the execution time will take. Take some time, to place the function outside the loop.

Bad example:

for ($i = 0; $i < count($array); $i++) {
  //stuff
}

Good example:

$count = count($array);
for($i = 0; $i < $count; $i++) {
  //stuff
}

12. Do not copy extra variables

Some people like to make their code more appealing by copying predefined variables to smaller-named variables. However, this is bad coding practices and hurt the performance and potentially double the memory usage of your script. Here is an example give by Google Code to illustrate good and bad examples of variable usage:

Bad example:

$description = strip_tags($_POST['description']);
echo $description;

Good example:

echo strip_tags($_POST['description']);

13. Protect your Script From SQL Injection

If you don’t escape your characters used in SQL strings, your code is vulnerable to SQL injections. You can avoid this by using the mysql_real_escape_string.

Here’s an example of mysql_real_escape_string in action:

$username = mysql_real_escape_string( $GET['username'] );

14. Use framework

Once you have learned about the basics of PHP, you may try out a PHP framework. There are tons of different PHP frameworks. However, many of those are design based on Model-view-contorller (MVC) software architecture. One of the reason that framework is being popular. It is because MVC architecture ensure clear spearation between data, logic and html which ensure ease of maintaince and developement. Also, it ensure different programmer to read and understand the codes easily.

Following are the popular PHP Frameworks, Template Engines & PHP based Content Management System

PHP Frameworks

Popular Template Engines:

Popular Content Management Systems