What are PHP bad coding practices?

In the midst of this barrage of poor coding there is a small but consistent push towards “good practice” in coding. Code needs to comply with a few fundamental requirements to be called “good” – it should be easy to read, easy to maintain, robust as possible, and (very importantly) fulfill the functional requirements for which it is being written (i.e. it does what it is supposed to do). Sounds pretty basic, you say. Sounds like common sense. In a word – yes. And we all know how “common” common sense is.

Why do I need to worry about it?

So why should you care? You’ve written lots of code, you know what it’s about, and you don’t have any trouble. What’s the big deal? Why should I go to the trouble required to apply “good coding” principles?

Essentially, if you apply these principles, then you will find your own work easier to read, easier to fix (for those of us who don’t always get it right the first time – not that you have this problem), easier to go back to in six months to maintain, more robust, and anyone else who has to deal with your code stands a better chance of understanding it. Let’s take a (brief) closer look at each one to drive it in.

Legibility

The code which you write (and this applies to the output it generates too) needs to be set out in such a way that you can read it. If you read a lot of other people’s source code, then you will have noticed that sometimes it is a lot easier than others. A simple piece of code becomes very difficult to read when it’s all cramped together with useless variable names and confusing logic. As for a complicated piece of code, you can forget it… Just because you know what something you’ve written does is no excuse for sloppy presentation.

Robustness

Here I’m mainly talking about programs that accept input. Users (bless their little hearts) are like children; no matter how clearly and carefully you explain what they have to do to use your program someone always manages to do something which they aren’t supposed to, be it putting in illegal characters (like “<” for html input forms) or pressing the wrong buttons. You need to try and make sure that your program is as forgiving as possible and check for these little lapses that users make. It will make your program much more popular because it will work (even if it’s just putting out error messages which make sense).

Debugging

Sure, somewhere out there it’s possible that a person writes perfect code every time, first time. It does what they expect, and there are no problems. For the rest of us, however, debugging code is just part of the normal routine. The easier to read and more logical the construction of your code, the easier it should be to find that niggling error (like that missing “;” on line 3,204 of 5,000 which keeps “magically” deleting itself).

Portability and Maintainability

It’s not always you who has to work with your code, and even if it is, what happens six months or a year after you wrote it? If it’s a simple piece of code, ok, but the bigger the project the more difficult it is to get a feel for it afterwards. Try to keep this in mind when you’re writing the code, and plan the logic and layout of your code in as comprehensible a way as possible.

Examples
So you have an idea of what good coding means, and why itshould be important to you, how do you go about applying the principles? In this next section I’ll take a look at what you can do to follow the spirit of good coding in your own work. Variable names, comments, white space, functions, external variable files, error checking, and consistency, are all both your tools and your allies in the fight for better code.

Variables are the bread and butter of your code – you slice them, dice them, cook them up, and then serve the results. Any time that you need a piece of information which you don’t have at coding time (meaning that it is supplied at “run-time”, when the program is actually running) you use a variable. Take a look at the code below.

 Bad choices for variable names

<?php 
$DxClwecoi = $_POST['name']; 
$DxClwecoi = stripslashes(trim($DxClwecoi)); 
echo $DxClwecoi; 
?>

Above code actually comes from a script which accepted someone’s name from a form and output it to the screen (yes, a real piece of code!). This is just one (shockingly painful) example of how not to name variables. You should try and use names which make sense. Figure 3.2 does the same as the code above, but with a much better choice of variable name.

<?php 
$user_name = $_POST['name']; 
$user_name = stripslashes(trim($user_name)); 
echo $user_name; 
?>

Isn’t that easier to understand? A little bit easier to read? Try to use variable names which indicate the type of content they are supposed to hold. In a language which is “typed” it is also a good idea to prefix your variable names to indicate what type they are. PHP is known as a weakly typed language, meaning that a variable can accept a number, and then be used for a string, or any other variable type. Other languages are strongly typed, meaning that you have to pick what type of data the variable will handle and then stick with it, or face some ugly looking error messages. Languages such as Visual Basic, C++, and Fortran are all strongly typed. Below we have given an example of some prefix suggestions for different types of variables.

Replace “[Variable]” with your variable name.

Byte – byte[Variable]
Boolean – bool[Variable]
Integer – int[Variable]*
Long (long int) – long[Variable]
Single (floating-point) – sgl[Variable]**
Double (double floating-point) – dbl[Variable]
Currency (scaled integer) – cur[Variable]
Date – date[Variable]
Array – arr[Variable]
Object – obj[Variable]
String – str[Variable]
Variant – var[Variable]

* Some languages distinguish between regular integers and long integers based on the size. Regular integers can only accept values from -32,768 to 32,767, while long integers can take -2,147,483,648 to 2,147,483,647.

** Single and Double are used for floating-point numbers, with sinlge ranging from -3.402823E38 to -1.401298E-45 for negative values and 1.401298E-45 to 3.402823E38 for positive values. Double type variables can handle 1.79769313486232E308 to -4.94065645841247E-324 for negative values and 4.94065645841247E-324 to 1.79769313486232E308 for positive values.

There are three different “mainstream” ways to name your variables:

Fixed case – variablename or VARIABLENAME
Mixed case – variableName
Underscored – variable_name
I personally favor the underscored, and dislike the fixed case (not forgetting that special server variables use all-caps). Mixed case is more commonly found in Java and JavaScript, while organisations like the phpBB team promote the use of the underscore. Feel free to mix and match. Whatever you choose to do, however, be consistent. Picking one method and sticking to it is more important than which one you choose, and will allow you avoid silly mistakes, especially in case-sensitive languages.

Comments are another useful tool. Comments shouldn’t be excessively long, but they should be used to describe what is going on. For complicated code you might want to put a summary at the top of the page. In PHP there are three ways to insert comments into your code. For a single line comment you can place either a “#” or “//” at the beginning to indicate the line should be ignored. For a multi-line comment it should be started with “/*” and terminated with “*/”.  Code below is an example of how to insert comments.

<?php 
/* This is a multi-line comment. The puropse of this script is to take a name from a form, strip it, and then output it to the browser. */ 

// Single line comments can use // or # 

// Get variable 
$user_name = $_POST['name']; 

// Trim the variable 
$user_name = stripslashes(trim($user_name)); 

echo $user_name; // Output to browser 
?>

Whether you use “//” or “#” for single line comments is your own choice. Historically they come from two different programming backgrounds: “//” is found in Java and JavaScript, while “#” is found in Perl. Stick with whatever choice you make. You’ll notice that in Figure 3.4 the last line of code echo $user_name; is followed by a comment. This is perfectly acceptable, as PHP will simply ignore anything after the “//” on that line. One note of caution – if you have spread a single line of code across multiple lines, do not use this in the middle – it could mess up your code. Code below demonstrates this.

Single line comments on multi-line code

<?php 
/* The code shown is one logical "line" in this example has no comment. You can break up lines of code like this across multiple lines in PHP (and other languages) */ 

if ($user_name == 'pineapple') { 
  echo 'User name: ' . $user_name; 
} 

// This works 
if ($user_name == 'pineapple') { 
  echo 'User name: ' . 
     $user_name;  // Ok comment 
} 

// This doesn't work 
if ($user_name == 'pineapple') { 
  echo 'Name: ' . // Bad comment 
     $user_name; 
} 
?>

In the first example the inline comment is after the end of the distributed line of code. In the second example, it is actually within the distributed line. While this doesn’t cause an error in PHP (4.3.1), it will in other languages, and should be avoided.

White space is another tool which can be used to enhance the legibility of your code. White space in PHP is interpreted in much the same way as white space in HTML; that is to say, it’s mainly ignored unless it’s part of a quoted value (i.e. a value inside of quotes, single or double). When you have programmatic structures (also known as control structures), such as loops or if-statements, distributing them across several lines can make them much easier to read.  Below example shows two of the same piece of code. Both examples work, but the second is much easier to read.

<?php 
// Bad Example 
if(isset($monkey)){ $monkey = stripslashes (trim( $monkey)); $monkey. = date(); $echo 'Value of $monkey = [' . $monkey . ']';}else{$monkey = 'Godzilla'; $monkey .= ' ' . date(mktime(22,3,5,4,5,9)); echo 'Monkey not declared but [' . $monkey . ']';} 

// Better Example 
if (isset($monkey)) { 
  $monkey = stripslashes (trim( $monkey)); 
  $monkey. = date(); 
  $echo 'Value of $monkey = [' . $monkey . ']'; 
} else { 
  $monkey = 'Godzilla'; 
  $monkey .= ' ' . date(mktime(22,3,5,4,5,9)); 
  echo 'Monkey not declared but [' . $monkey . ']'; 
}  
?>

There is a debate about the use of tabs vs spaces for indenting “blocks” of code. I personally favor the use of spaces (2 per level), but if you have a good text editor then you may be able to define the number of spaces equal to a tab, so you can more easily customize it. Pick whichever you prefer and stick with it.

Functions are another, very powerful, tool which you can employ to aid your code. The basic idea behind functions is that you can create a small sub-routine, make it work, and then just call it from many places in your code. This has two key benefits: in the first place it means that once you have the code working it can be used repeatedly without any extra effort, and secondly it reduces the amount of typing you have to do. Code below provides a basic template for defining a function and calling it, but I would suggest you read in the PHP manual if you need help with functions.

Basic template for a function and how to call one

<?php 
function function_name (arguments) { 
  // Code of function goes here 
} 

// To call function 
function_name (arguments); 
?>

The final method I’ll cover for making your code “good code” is error checking. Any time that you do something with files, or accept data from the user, you run the risk of something not working. If you check for these problems, then you can help yourself and your users by providing helpful information (as opposed to some of the default error messages, which, depending on the language, can be decidedly unhelpful, and even confusing). We’ll take a look at a couple brief examples of where you can do this, and then I’ll discuss some other areas to keep in mind.

Let’s say that you are using a resource file to get data. If for some reason that file is not available then the user will see an ugle message in the browser. If, however, you use the or die() command (which is an alias for the exit(); command) as shown in following code, then you can choose to output a much friendlier statement.
Using the or die() command

<?php 
$file = 'resource.txt'; 
$fp = fopen($file,'r+') 
     or die('Sorry, the file was not available.'); 
?> 

Another situation where you might commonly use a “catch-all” is with the switch() control structure. If you always remember to put in a default option, as shown in following code below, then you are one step closer to user-friendly robust code. In the example $user_name is presumed to have come from a form on another page.

Using default in the switch control structure

<?php 
$user_name = $_POST['user_name']; 
$user_name = stripslashes(trim($user_name)); 
switch ($user_name) { 
  case 'Alfred': 
    echo '<a href="alfreds_page.html">Enter</a>'; 
    break; 
  case 'Frank': 
    echo '<a href="franks_page.html">Enter</a>'; 
    break; 
  default: 
    echo 'Sorry, but you aren\'t on my list!'; 
    break; 
} 
?>

This way, if there is no match, at least something is always done. When in doubt, include a catch-all, just in case. Other areas that you should keep an eye on is whether or not variables exist using the isset() function and are not empty (compare with == ”), whether there are any extra spaces or hard returns in strings from forms (which you can fix using the trim() function), and really just make sure that anywhere something could kill your app a user-friendly output is generated. To find more help on error catching, try doing a search in google.

Review

We have taken a look at what good coding practice is, why it should be important to anyone who writes code, and how to apply the principles of good coding. Using white space, logical variable names, white space, comments, and functions all contribute to the legibility, debugging, portability, and maintainability or your code. Using robust programming constructs which deal with possible errors can also help to keep users happy even if your code should fail. Above all, be consistent with your coding.

As a final note, irrespective of the brilliance of your code, or the power of the tools you use to help you process your source code, following the spirit of good coding will not only improve your code, it will also make you more popular with your co-workers and your end users as you produce more functional, robust applications.

Add a Comment

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

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote