PHP Coding Guidelines & Best Practices

PHP is the most widely-used language for programming on the web. Here are thirty best practices for beginners wanting to gain a firmer grasp of the fundamentals.Coding Standards are an important factor for achieving a high code quality. A common visual style, naming conventions and other technical settings allow us to produce a homogenous code which is easy to read and maintain. However, not all important factors can be covered by rules and coding standards.

 

Read PHP Manual : The PHP manual is incredibly thorough and has truly helpful comments following each article. Before asking questions or trying to figure out an issue on your own, save some time and just head straight to the manual.

Always use Meaningful, Consistent Name Standard : camelCase and underscores are two popular naming standard. In camelCase, the first letter of each word is capitalized, expect for the first word while underscores, adds underscore between words, like mysql_real_escape_string().

Turn on Error Reporting : Error reporting in PHP is very helpful. You’ll find bugs in your code that you might not have spotted earlier, as not all bugs keep the application from working. There are different levels of strictness in the reporting that you can use, but E_ALL will show you the most errors, critical and warnings alike.

Once you’ve gotten your application ready for production, you’ll want to turn off error reporting, or your visitors will see strange errors that they don’t understand.

Try an IDE : IDE’s (Integrated Development Environments) are helpful tools for any developer. While they’re not for everyone, an IDE definitely has its place. IDE’s provide tools like

syntax highlighting
code completion
error warnings
refactoring (reworking).

Use the DRY approach : ‘Do not Repeat Yourself’ abbreviated for DRY, which is one of the best and useful programming concept and should be used in any programming language like PHP, Java, and C#. Using the DRY approach ensure that no redundant code is there.
A piece of code, violating DRY refers as the WET solution. WET stands for ‘We Enjoy Typing’ or ‘Write Everything Twic’. Check out below given code:
DRY and WET approaches

$mysql = mysql_connect ( ‘localhost’, ‘mysqladmin_uid’, ‘mysqladmin_pwd’ );
mysql_select_db( ‘DB_NAME’ ) or die( “Sorry !! No database selected!”);

The above given code is based on the WET approach as the relevant parameters are hardcoded. Below given is the DRY approach and code can be updated to.

$db_host = ‘ localhost ‘; $db_user = ‘ mysqladmin_uid ‘; $db_password = ‘ mysqladmin_pwd ‘; $db_database = ‘ DB_NAME ‘; $mysql = mysql_connect($db_host, $db_user, $db_password); mysql_select_db($db_database);

 

Avoid putting phpinfo() in your web root : Phpinfo is a useful function. Users just have to create a simple PHP file with <?php phpinfo(); ?> and have to paste it to the server as you know everything about your server environment.But, there are many programmers would place the file contain phpinfo() in the webroot, which is consider very insecure practice. It results into it could potentially speel doom from the server.Ensure to place phpinfo() in the secure sport and it should be delete once you are done.

Try ORM : Using the nifty object relational mapping (ORM) is an excellent ideas to write object-oriented PHP. With object relational mapping, one can easily convert their data between relational databases and object-oriented programming languages. ORM allows working with databases like you are working with classes and objects in PHP. Developers can find loads of ORM libraries for PHP such as Propel and ORm is created into PHP frameworks like CakePHP.

Ensure to Comment: It is advisable to leave comment inside your source code as it is essential when you are involving 5-10 programmers in your project. Comments help to the people, who are maintaining a project from a long time ago.
It is recommended to get educated with some PHP Documentation packages like phpDocumentor to maintain a high quality of comment standard and also take extra time to do it.

Try a PHP Framework : Those developers, who have learned the fundamentals of PHP, can try some PHP frameworks. Different types of PHP frameworks are available that mostly designed on the basis of Model-View Controller (MVC) software architecture.Moreover, one can learn many interesting and latest things by using a PHP framework. Those who want to create some awesome PHP applications with ease can use framework like Symfony, CakePHP, CodeIgniter, and Zend.

“Tier” your Code : Tiering applications means separating the different components of the code into various parts. It allows changing code easily in future. If you want to know how to how to tier your PHP applications for easier maintenance then read this article.

Always Use

<?php ?> 

<?

echo “Hello world”;
?>
<?=”Hello world”; ?>

<% echo “Hello world”; %>

While these do save a few characters, all of these methods are depreciated and unofficial. Stick with the standard <?php ?> as it will be guaranteed to be supported in all future versions.

Install MAMP/WAMP : MySQL is one of the most popular types of database that can be used along with PHP. Installing MAMP (Mac) or WAMP (Windows) is possible, if you want to set up a local environment to develop and test PHP applications on your computer.Developers can find the installation process of MySQL on their computer is tedious one and both of such software packages are drop-in installs of MySQL.

Use Objects (or OOP) : Objects are used by Object-oriented programming that represents parts of the application. Along with breaking the code into separate and logical sections, OOP helps to minimizes code repetition and make it much easier to change for future correction. To know more about write-up on object-oriented programming with PHP.

Know the Difference Between Single and Double Quotes : It is more efficient to use single quotes in strings as the parser doesn’t have to sift through the code to look for escaped characters and other things that double quotes allow. Always try to use single quotes whenever possible.

Never, Ever Trust Your Users : 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();
}
?>

Always Store Passwords with Encryption : Many PHP beginners often plunk sensitive data like passwords into the database without applying any encryption. Consider using MD5 to encrypt passwords before you put them into the database.

echo md5(‘yourpassword’); 

use Output Buffering : Output buffering is a simple way to greatly improve the performance and speed of your PHP script. Without output buffering, your script will show the HTML on the page as it’s processed – in pieces. Adding output buffering allows the PHP to store the HTML as a variable and send it to the browser in one chunk.

To enable output buffering, simply add ob_start() like so at the top of the file.

<!DOCTYPE html>
<?php ob_start(‘ob_gzhandler’); ?>
<html lang=”en”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<title>untitled</title>
</head>
<body>

</body>
</html>
<?php ob_end_flush(); ?>

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 either using the mysql_real_escape_string, or by using prepared statements.

Here’s an example of mysql_real_escape_string in action:

$username = mysql_real_escape_string( $GET[‘username’] );

Prepared Statement: 

$id = $_GET['id'];
$statement = $connection->prepare( "SELECT * FROM tbl_members WHERE id = ?" );
$statement->bind_param( "i", $id );
$statement->execute();
Upgrade to the Latest Version of PHP : While it seems like a common sense thing, many people don’t upgrade PHP as often as they should. There are lots of performance increases between PHP 4 and PHP 5. Check your server to make sure you’re up to date.

 

 

 

Leave a comment