Tizag.com Webmaster Tutorials - A collection of webmaster tutorials from HTML to PHP.

Saturday, March 3, 2012

PHP Basic Coding Standard for Web Application

Why coding guidelines are required?


Guidelines are only useful if they are followed. It is arguable that we can get away with different coding styles if every team member works on a different section which is encapsulated and therefore their
coding style doesn’t affect the other developers. Unfortunately, this only holds true until a developer leaves and someone else has to take over their role.

There are few guidelines which can be followed while coding in PHP

  1. Use ""

  2. Use four spaces for indentation. Don't use tab literal characters because different
    computers use different setting for tab.

  3. Quoting strings: Strings in PHP can either be quoted with single quotes ('') or double quotes ("").
    The difference between the two is that the parser will use variable-interpolation in double-quoted strings, but not with single-quoted strings. (figure 1)




  1. Put a space after control keywords like if and for. Put a space around operators like =, <
    etc. (refer fig 2)

  2. Strings must be concatenated using the "." operator. A space must always be added before and after the "." operator to improve readability:
$company = 'Electronic' . ' ' . 'Medical' . ' ' . 'Records';
$string = 'Foo' . $bar;

$string = "Foo $bar"; //
you can use double quotes and add the variable inside; else use single quote


  1. Make sure that Parentheses hug their contents with proper indentation. (refer fig 2)
  1. Case and Capitalization:


I.
Function names should be as verbose as is practical to fully describe their purpose and
behavior. Name the functions using lowerCamelCase. When a function name consists of more than one word, the first letter of each new word must be capitalized. E.g. when we are retrieving a patient’s average pulse rate through a function. The function name should be patientAveragePulseRate().


II.
Variable names may only contain alphanumeric characters. Numbers are permitted by but try avoiding it. Variables should have more descriptive names. Say when a variable is set for pulse rate so set the variable name as $pulseRate


III.
Name constants using UPPERCASE separated by underscore characters. Say ‘UPLOAD_FILE_LOCATION’


IV.
Name classes using UpperCamelCase.


V.
Write true, false and null in lowercase.


  1. For files containing only PHP code, omit the closing "?>"

a. The closing ‘?>;’ is not required in php files unless it is in a file being included and the
following code is not php. It becomes impossible to accidentally add white space to the end of the file. Therefore, output cannot be sent to the browser before HTTP page headers are modified.



b. If ‘?>’ used, any whitespace following the closing tag, whether introduced by the developer, user, or an FTP application, can cause unwanted output, PHP errors, or if the latter are suppressed, blank pages. For this reason, all PHP files should OMIT the closing PHP tag, and instead use a comment block to mark the end of file and its location relative to the application root. This allows you to still identify a file as being
complete and not truncated. (refer fig 2).





  1. Turn on all error reporting. If a code works with E_ALL set, then it will also work with any other error reporting configuration, including when all error reporting is turned off.







  2. Shortcut constructs: Replace if statements where you are assigning one of two values to a variable based on a conditional.

    if ( isset($_POST['city']) )

    {

    $city = $_POST['city'];

    }

    else

    {

    $city = '';

    }

The above code works perfectly but it is not a clearest way if we want to run through a list of different variables and do a similar operations. The best way to do it in a more compact way mentioned below.

$city = isset($_POST['city']) ? $_POST['city'] : '';



  1. Code Commenting: Code commenting is required that others (and developer after a time span) can quickly understand what is going on in the codes. Following DocBlox or phpDocumentor comments standards are again too time consuming. So lets follow a few commenting logic mentioned below.


I.
Page Level Commenting: On the top part of php file the use of the php file should be
clearly mentioned. (fig 3)



II. Comments related to a class or specific function: On the top each functions declaration
a small block of comments to be written. (fig 4)
III. Single Line Comment: It can be on a line of its own, or it can be appended to the end of a line of code. (fig 5)

IV. Multi Line Comment: Multi-line comments are useful when you have notes you want to make in the code that will take up more than one line. The ability to mark blocks of
lines as comments avoids the necessity of placing the single line comment marker at the start of each comment line. (fig 6)





  1. SQL Code Layout: When writing SQL queries, capitalize all SQL keywords (SELECT, FROM, VALUES, AS, etc.) and leave everything else in the relevant case. Lets keep a few points in mind where we
    can increase the performance of a query.


I.
Select only the fields you need. Never use "Select *" -- Specify only the fields
you need; it will be faster and will use less bandwidth.



II.
Filter as much as possible. The 'WHERE' Clause is the most important part for optimization




III.
Don't use DISTINCT when you have or could use GROUP BY. If all you need is to remove
duplicates then use DISTINCT.




IV.
Avoid using IN(...) when selecting on indexed fields, It kills the performance of SELECT
query.




V.
Try using a JOIN instead of a sub query. Joins are expensive in terms of time. Make sure
that you use all the keys that relate the two tables together and don't join to
unused tables -- always try to join on indexed fields.




VI.
SQL Injection Prevention: SQL injection refers to the act of someone inserting a MySQL
statement to be run on your database without your knowledge. Injection usually
occurs when we ask a user for input. Lets consider three things which will help
us to prevent SQL injection attempts.



a. Using PHP Data Objects: PDO is a PHP extension that work like class letting you access database more fast and secure. Say $db is a success PDO connection.

$sth = $db->prepare('SELECT field FROM table WHERE id = :id');

$sth ->execute(array(':id' => $_GET['id']));

$rows = $sth ->fetchAll();




b. mysql_real_escape_string(): A function that escape the unsafe character before sending the MySQL query.





VII.
Minimum header requirement of header should be followed as mentioned below points (fig 8).



a. The DOCTYPE should declare the appropriate version of the HTML used in the document.



b. The xmlns is required for validation.



c. Minimum file header comments should include description, author and date.



d. The meta element declare properties of the document.



e. content-type is essential for validation and for local computer use.



f. description is used by search engines keywords and author help document searches.




  1. Validation of file: The HTML code should be validated against the DOCTYPE, HTML validation service at http://validator.w3.org/ . A comment within the header should indicate if and when the code was validated.

  2. Don’t put phpinfo() in your Webroot. This is a really insecure practice, and if trying eyes gain access, it could potentially spell doom for your server. Make sure phpinfo() is in a secure spot, and as an extra measure.

  3. 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. Refer url:
    http://dev-tips.com/featured/output-buffering-for-web-developers-a-beginners-guide
    for detailed explanation
    . (refer fig 9)







  1. Don’t Copy Extra Variables: This is redundant and could potentially double the memory of your script. Google Code has bad and good examples of variable usage. PHP implements “copy-on-write” memory management. This basically means that you can assign a value to as many variables as you like without having to worry about the data actually being copied. “Doubling the memory,” this actually is a common misconception.







  1. Make sure the page execution time is minimum. To measure each page rendering
    time we may consider a small script (fig 10). One can use any logic for
    similar functionality.









  1. After a module is done make sure that it is comparable with all versions of popular browsers like IE, MozilaFirefox, Chrome, Safari and Opera.





Note: Always validate the pages with a validation
service (http://validator.w3.org/). Validation keeps your documents up to the
standards, and free of errors. If non-standard elements have been used, and the
code does not validate, then the comment should indicate what non-standard
elements have been used and why.