30 PHP Best Practices for Beginners

30+ PHP Best Practices for Beginners

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.

Editor’s Note: The “Best Practices” series has been my baby for three articles now. However, due to my focus on the CI video series, I’ve decided to hand off this next entry to Glen. Having said that, I’m not very good at keeping my mouth shut! I thought it might be fun to sporadically add a few rebuttals to his tips. I hope he doesn’t mind!

1. Befriend the PHP Manual

If you’re new to PHP, then it’s time to get acquainted with the awesomeness that is the 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. Odds are the answer to your question is already nestled in a helpful article at the PHP.net site.

2. 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.

3. 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)

And many other features. There are plenty of great IDEs out there that support PHP.

Try an IDE

4. Try a PHP Framework

You can learn a lot about PHP just by experimenting with PHP frameworks. Frameworks like CakePHP or CodeIgniter allow you to quickly create PHP applications, without having to be an expert with PHP. In a sense, they’re almost like PHP training wheels that show you what a PHP application should look like, and show you valuable programming concepts (like separating the logic from the design, etc.).

Rebuttal: I personally wouldn’t recommend that beginners use a framework. Learn the fundamentals first. :)

5. Learn the DRY Approach

DRY stands for Don’t Repeat Yourself, and it’s a valuable programming concept, no matter what the language. DRY programming, as the name implies, is ensuring that you don’t write redundant code. Here’s an example from Reinhold Weber:

Learn the DRY approach

This code…

$mysql = mysql_connect('localhost', 'reinhold', 'secret_hash');
mysql_select_db('wordpress') or die("cannot select DB");

now with the DRY approach:

$db_host = 'localhost';
$db_user = 'reinhold';
$db_password = 'secret_hash';
$db_database = 'wordpress';

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

You can read more about the DRY programming principle here and here.

6. Indent Code and Use White Space for Readability

If you don’t use indentations and white space in your code, the result looks like a Jackson Pollack painting. Ensure that your code is readable and easy to search because you’ll most definitely be making changes in the future. IDEs and advanced text editors can add indentation automatically.

7. “Tier” your Code

Tiering your applications is nothing more than separating the different components of the code into different parts. This allows you to easily change your code in the future. NETTUTS writer Jason Lengstorf has written an excellent article on how to tier your PHP applications for easier maintenance.

8. Always Use <?php ?>

Often times programmers try to take shortcuts when declaring PHP. Here are a few common ones:

<?
    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.

9. Use Meaningful, Consistent Naming Conventions

Naming this isn’t just for your own good. There’s nothing worse than trying to find your way through some other programmer’s nonsensical naming conventions. Help yourself and others by using names that make sense for your classes and functions.

10. Comment, Comment, Comment

Aside from using white space and indentations to separate the code, you’ll also want to use inline comments to annotate your code. You’ll thank yourself later when you’re needing to go back and find something in the code, or if you just can’t remember what a certain function did. It’s also useful for anyone else who needs to look over your code.

11. Install MAMP/WAMP

MySQL is the most popular type of database to use with PHP (though it’s not the only one). If you’re wanting to set up a local environment to develop and test your PHP applications on your computer, look into installing MAMP (Mac) or WAMP (Windows). Installing MySQL on your own computer can be a tedious process, and both of these software packages are drop-in installs of MySQL. Clean and simple.

Install MAMP/WAMP

12. Give your Scripts Limits

Putting a time limit on your PHP scripts is a very critical thing. There are times when your scripts will fail, and when they do, you’ll want to use the set_time_limit function to avoid infinite loops and database connection timeouts. The set_time_limit puts a time limit on the maximum number of seconds a script will run (the default is 30). After that time period, a fatal error is thrown.

13. Use Objects (or OOP)

Object-oriented programming (OOP) uses objects to represent parts of the application. Not only is OOP a way to break your code into separate, logical sections, it also reduces code repetition and makes it much easier to modify in the future. If you’re wanting to learn more, DevArticles has a great write-up on object-oriented programming with PHP.

14. 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.

Rebuttal: Actually, that’s not necessarily true. Benchmark tests show that, when testing strings without variables, there are definite performance benefits to using double quotes.

15. Don’t Put phpinfo() in your Webroot

Phpinfo is a beautiful thing. By simply creating a PHP file that has

	<?php phpinfo(); ?>

and dropping it onto the sever somewhere, you can instantly learn everything about your server environment. However, a lot of beginners will place a file containing phpinfo() in the webroot of the server. This is a really insecure practice, and if prying eyes gain access, it could potentially spell doom for your server. Make sure phpinfo() is in a secure spot, and as an extra measure, delete it once you’re done.

don't put phpinfo() in your web root

16. 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();
	}
	?>

17. 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('myPassword'); // renders - deb1536f480475f7d593219aa1afd74c

Rebuttal: Keep in mind, however, that MD5 hashes have long since been compromised. They’re absolutely more secure than not, but, with the use of an enormous “rainbow table,” hackers can cross reference your hash. To add even more security, consider adding a salt as well. A salt is basically an additional set of characters that you append to the user’s string.

18. Use Database Visualization Design Tools

If you’re finding it difficult to plan and modify databases for your PHP applications, you might look into using a database visualization tool. MySQL users can work with DBDesigner and MySQL Workbench to visually design your databases.

use database visualization design tools

19. 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.


Rebuttal: Though not required, it’s generally considered to be a good practice to go ahead and append the “ob_end_flush();” function as well to the bottom of the document. P.S. Want to compress the HTML as well? Simply replace “ob_start();” with “ob_start(‘ob_gzhandler’)”;

Refer to this Dev-tips article for more information.

<!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(); ?>

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

and a prepared statement:

	$id = $_GET['id'];
	$statement = $connection->prepare( "SELECT * FROM tbl_members WHERE id = ?" );
	$statement->bind_param( "i", $id );
	$statement->execute();

By using prepared statements, we never embed the user’s inputted data directly into our query. Instead, we use the “bind_param” method to bind the values (and escaping) to the query. Much safer, and, notably, faster when executing multiple CRUD statements at once.

Read more on creating secure PHP applications at Nettuts.

21. Try ORM

If you’re writing object-oriented PHP, then you can use the nifty object relational mapping (ORM). ORM allows you to convert data between relational databases and object-oriented programming languages. In short: ORM allows you to work with databases the same way that you work with classes and objects in PHP.

There are plenty of ORM libraries for PHP like Propel, and ORM is built into PHP frameworks like CakePHP.

22. Cache Database-Driven Pages

Caching database-driven PHP pages is an excellent idea to improve the load and performance of your script. It’s really not all that difficult to create and retrieve static files of content with the help of our good friend ob_start(). Here’s an example taken from Snipe.net:

	// TOP of your script
	$cachefile = 'cache/'.basename($_SERVER['SCRIPT_URI']);
	$cachetime = 120 * 60; // 2 hours
	// Serve from the cache if it is younger than $cachetime
	if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) {
	include($cachefile);
	echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->";
	exit;
	}
	ob_start(); // start the output buffer
	// Your normal PHP script and HTML content here
	// BOTTOM of your script
	$fp = fopen($cachefile, 'w'); // open the cache file for writing
	fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file
	fclose($fp); // close the file
	ob_end_flush(); // Send the output to the browser

This bit of code will use a cached version of a page that is less than 2 hours old.

23. Use a Caching System

If you’re wanting a more robust caching system, there are a few caching scripts for PHP that might be more complete than the above example.

use a caching system

24. Validate Cookie Data

Cookie data, like any data passed on the Web, can be harmful. You can validate cookie data with either the htmlspecialchars() or mysql_real_escape_string().

25. Use Static File Caching Systems

Aside from using database caching systems like Memcached, you might also want to try a templating system to increase performance in your PHP applications. Smarty is a robust templating system has caching built into it.

26. Profile your Code

Profiling your code with a tool like xdebug can help you to quickly spot bottlenecks and other potential problems in your PHP code. Some IDEs like Netbeans have PHP profiling capabilities as well.

27. Code to a Standard

Once you’ve gotten the ropes of PHP down, you can start learning about coding to a standard. There are differences between standards out there (say Zend and Pear), and finding one and sticking with it will help with the consistency of your coding in the long run.

28. Keep Functions Outside of Loops

You take a hit of performance when you include functions inside of loops. The larger the loop that you have, the longer the execution time will take. Take the extra time and line of code and place the function outside of the loop.


Editor’s Note: Think of it this way. Try to remove as many operations from the loop as possible. Do you really need to create that variable for every iteration of the loop? Do you really need to create the function each time? Of course not. :)

29. Don’t Copy Extra Variables

Some people like to try and make their code more appealing by copying predefined variables to smaller-named variables. This is redundant and could potentially double the memory of your script. Google Code has bad and good examples of variable usage:

Bad

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

Good

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


Rebuttal: In reference to the comment about “doubling the memory,” this actually is a common misconception. 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. While it’s arguable that the “Good” example exemplified above might make for cleaner code, I highly doubt that it’s any quicker.

30. 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.

31. Reduce the Number of Database Queries

Any way that you can cut back on the number of database queries, the better your PHP script will perform. There are tools like Stace (Unix) and Process Explorer (Windows) that allow you to find redundant processes and how you might combine them.

Reduce the number of database queries

32. Don’t be Afraid to Ask for Help

It’s only human nature to want to hide the fact that we don’t know much about a certain topic. Nobody likes being a n00b! But how are we going to learn without asking? Feel free to use forums, IRC, StackOverflow to ask more seasoned PHP developers questions. The PHP website has a page on getting PHP help.

Have any rebuttals of your own? I’m sure you do! Let’s start the debate.


Add Comment

Discussion 177 Comments

Comment Page 3 of 3 1 2 3
  1. sarah says:

    its actually interesting to watch everyone’s comments and to observe your points and objections. A useful learning curve for those new at this, especially watching out for the what not to do’s and for those that have made the mistakes an ironic smile maybe….

    IMO, as one comment implied does your code need explaining? and another implication isn’t it better to learn the fundamentals rather than learn from a tool that does it for you? and google does indeed have god examples for extra variables, but what ever happened to the learning curve?

    Some honesty and some irony…I love it!

  2. Raj Sandhu says:

    Nice Tutorial, thanks very much

  3. Very interesting info. Great post!

  4. James Tang says:

    Great Post! I’d like to share it and translate it into Chinese if you like!

  5. Gagan says:

    Really interesting to look at for all the new php concepts….

  6. Really nice tutorials… and a good guideline for beginners
    But I also need nice tutorials for learning PHP Frameworks!!!

  7. chessmonster says:

    very nice tutorial! but uh.. in the future i would like to migrate to ubuntu to learn PHP and i just want to ask if the tools that you have posted here would also be available with the linux ubuntu like the IDE and database visualization tools? does ubuntu support those apps? thanks :D

  8. Joe says:

    Thanks for the tips!

  9. Tomwrong says:

    Some good points here, my top tip is to indent your HTML separately to your PHP. It may look a little odd to some, but it really helps in practice when you have a heavy amount of HTML to pin. Notice the strict hard-left alignment of the starting PHP tags when stating a block of logic.

    blah, doen’t matter about this

    WHAT ARE CHANCES!!!!

  10. پزشکی says:

    Great Post! I’d like to share it and translate it into Chinese if you like!

  11. Very interesting info. Great post!

  12. chrelad says:

    Nice article. Didn’t agree with all of your points; but quite a few I did.

  13. Rajaguru Paramasamy says:

    Excellent info!!!

  14. Brian says:

    “validate” isn’t really the right word for #24. I would write it as “You can make cookie data safe by using mysql_real_escape_string() when storing it to the database, and htmlspecialchars() when displaying it on an HTML page”.

  15. Atiq says:

    Great Article for beginners i learn lot via this article.

  16. Arthur says:

    Thanks allot for your article, big job.
    But I whant to notice you, that DRY example from Reinhold Weber dont work anymore.

  17. Arun says:

    This article is very useful for the developers thankyou !

  18. Thanks a lot for the tips.. Specially for the reference to the sources to read about..

  19. Thisara says:

    Hey thanx, this was really helpfull.

  20. frostymarvelous says:

    Excellent article overall, but you got one thing wrong.

    Shorttags are not deprecated. They will NOT be removed. Actually lerdorf stated that, the purpose of php is to template websites and thus, they won’t be removed since they are made for templates.

  21. gmanon says:

    Thanks it’s a very good article!

    I will consider from now and on to use output buffering and to create database cash driven pages. I also like your method to prevent sql injection. It’s different to what I’ve seen.

  22. simranjit says:

    hi,

    I am having a number of questions related to PHP. can you please email me so that i can send you an email with questions?

    Thanks
    Simran

  23. towry says:

    YES,This article is very help to me, and I am a newer in PHP, I know some OOP basic knowledge. I think the next step to be done is to practice and if i get some question,I should go to the manual first.
    Please sorry for my bad English,I am a Chinese.

  24. Phil says:

    Your example of a ‘properly secured form’ is the opposite of a secured form.

    You have quoted an example of a form that is vulnerable to variable injection because the variable is not initialized, and made it appear to readers as though this is how they should write a secured form!

    The variable $login must be set to false at the top of the code or register_globals = on would allow it to be overwritten. You should really be more careful when dispensing this sort of advice…

  25. aiman says:

    This is the worst tutorial I ever saw. Totally misleading people!
    @2. Turn OFF Error Reporting -> to do not expose your errors public.(security). use debugger.
    @3. Try an IDE -> try brain, the best practice is the Notepad.
    @8. Always Use -> NEVER use ?> to avoid injections
    @15. Don’t Put phpinfo() in your Webroot – Don’t Put phpinfo() in ALL
    @20. Protect your Script From SQL Injection -> SET NAMES is usually used to switch the encoding from what is default to what the application needs. This is done in a way that mysql_real_escape_string doesn’t know about this. This means if you switch to some multi byte encoding that allows backslash as 2nd 3rd 4th… byte you run into trouble, because mysql_real_escape_string doesn’t escape correctly. UTF-8 is safe…

    Safe way to change encoding is mysql_set_charset, but that is only available in new PHP versions
    /Stefan Esser/
    @24. Validate Cookie Data -> Validate ANY Data
    @29. Don’t Copy Extra Variables -> Filter and Unset unnecessary vars. Never use the way from example: echo strip_tags($_POST['description']);
    @30. Upgrade to the Latest Version of PHP -> NO! note most of servers is using 5 – 5.2.7 where latest stable is 5.3.8.

  26. Daniel says:

    This was a great read. I am a novice PHP programmer and just now getting into more advanced web development. The suggestions you have provided and links will really help me in the upcoming projects I have. Thanks.

  27. Mark Ramsey says:

    Fantastic article. People like you are what makes the web/world great – thank you ;-)

  28. Col. Shrapnel says:

    like many such lists, it is very inconsistent and dont by a person with much enthusiasm but little knowledge. (2) is msileading (for the turn off part), (5) is confusing (why DRY is actually longer?), (8) is just not true, (14) is ridiculously wrong, (23) and (25) are mutually exclusive. But most terrific part is it’s inconsistency: Among really great things like (26) there are ridiculous ones like (29)

  29. very very very useful topics .. really liked it .. thanks for all the stuff .. cheers

  30. I have read one by one topic.and finally thanks you for this helpful information.also for those web source that is very help for me for learning.

  31. J says:

    Good article. By the way, I found a typo in number 31: “There are tools like Stace (Unix) ”

    Stace is missing an ‘r’ (Strace).

  32. dhanesh mane says:

    hey these are really very very helpful tips.

    thanks for sharing.

    Thanks
    Dhanesh Mane

  33. Zeeshan Umar says:

    Thanks for sharing such wonderful article, i am new to php and it is really helpful for me

  34. Habeeb Perwad says:

    G00d One…

  35. johnatan says:

    Thanks for sharing! very good!

  36. i really like it. and also bookmark it for future us.. Thanks for sharing.

  37. Paul M. says:

    Neither MD5 nor SHA1 actually encrypt anything. They simply create hashes, which you then store so you don’t have to store the plaintext password. You then compare the hashes; you never ‘decrypt’ anything.

    I split this hair because I have to explain it every single freakin’ day, and it would help if people got it right in ‘blog posts like this one, which is otherwise quite excellent. :-)

  38. Adam Riddick says:

    In your article, you say both ‘Consider using MD5 to encrypt passwords before you put them into the database.’ and then ‘MD5 Hashes’ .. So I would like to make some corrections.

    As Paul M. stated, MD5, and sha1, are hashing algorithms, which is NOT encryption, far from it. Encryption and be reversed, using the method of decryption. Hashing, cannot be reversed, and this is it’s biggest use when it comes to storing passwords.

    At no point do you, or anyone else, need to be able to gain access to your user’s passwords, and so they should not be saved in a retrievable form.

    Your website should use a salt value when it comes to authentication, an overall website salt that is added to a users password before it is hashed (MD5 and SHA1 aren’t the safest, but other alternatives exist.).

    I like to take this a step further by adding a second, user based salt, or random length, which nobody will ever see. With two salt values added to a password before it is hashed, or so some other intricate design, you are massively increasing the security of your user’s passwords, and thus their trust.

    I would also like to add that database queries should use prepared statements, either through PDO or MySQLI (I am a PDO man myself, because they are better.). This negates the need for having to hard-code injection protection.

    • Ixalmida says:

      Note: Oracle strongly discourages using PDO with MySQL. PDO does not fully support MySQL’s capabilities and does not perform as well as MySQLi.

  39. Sanjeeb Sahu says:

    Hey thanks for sharing the new PHP concepts. Its really helped me..
    Keep sharing….

  40. Vishal says:

    Hello,
    I am new to PHP and this post really pointed out to stuff i never knew about. Thanks! Bookmarked! :)

  41. lucb1e says:

    Number 16 is very bad practice. If you went trough the trouble of enabling https (I assume that’s what is meant by “redirect to secure environment”), at least do it right and make the users submit the form data over https. It’s less a problem to have the user’s cookie compromised than to have the password sent and the session secured…

Comment Page 3 of 3 1 2 3

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.