Logo
Code Ranks ×

PHP Best Practices | web tutorial 2019| coderanks

22/06/2019  .   3 minutes, 18 seconds to read  .   Posted by Admin
#php #best-practices #WebDevelopment #PHPCodigniter #learnphp #phptutorial

PHP is the most popular 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

 In PHP error reporting is very useful. It help us to spot errors.

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. Let take an example here.

$mysql = mysql_connect('127.0.0.1', 'admin', 'admin_password');

mysql_select_db('dbname') 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 = 'dbname';

$mysql = mysql_connect($db_host, $db_user, $db_password);

mysql_select_db($db_database);

You can read more about DRY at here

3. Highly recommend to use <?php ?>

Many developers use short cuts  while 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 ?>.

4. 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().

class Foo {
    public function someDummyMethod() {
    }
}
function my_procedural_function_name() {
}

5. Prevent Deep Nesting

The deep nesting increases reading complexity.

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;

 }

}

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;

  }

}

6. Remember to Comment, Comment & Comment

Please ensure that you leave comment inside your source code.The comment is very important.Comment are used to indicate the functionality and helps programmers to modify code easily.
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.

7. Never trust your user

A great way to keep your site hacker-free is to always initialize your variables to safeguard your site from XSS attacks

 <?php

if (correct_user($_POST['user'], $_POST['password']) {

     $login = true;

}

if ($login) {

     forward_to_secure_environment();

}

?>

8. Use a cache mechanism

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

9. Keep Functions Outside of Loops

The keeping of function inside the loop reduce the performance. It will result in to maxmium execution time depending on the loop value.

Bad example

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

  //stuff

}

Good example:

$count = count($array);

for($i = 0; $i < $count; $i++) {

  //stuff

}

10. Do not copy extra variables

Copying extra varibale hurts performance and potentially double the memory usage of your script. 

Bad example

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

echo $description;

Good example

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

11. 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'] );

12. Use framework

There are tons of different PHP frameworks. However, many of those are design based on Model-view-contorller (MVC) software architecture. It is because MVC architecture ensure clear spearation between data, logic and html which ensure ease of maintaince and developement.

MVC

PHP Frameworks

Popular Template Engines

Popular Content Management Systems