Try Tuts+ Premium, Get Cash Back!
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.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://droidfeed.com Ivan

    Excellent. I’m actually saving this for future reference.
    Specially to try those caching systems

  • Paul

    1st -KaaaaaaPING!

    Awesome Tut!

    • http://ccpmultimedia.com Connor Crosby

      NOT!

    • Keith

      No, your second and how is that comment valuable?

  • http://melissa-brandon.com Brandon Hansen

    Had to laugh- #6 Indent your code. #20- Impossible to read because not indented at all.

    • http://www.jeff-way.com Jeffrey Way

      Heh. That is funny. That’s more an issue with the highlighting plugin we use. It can be a pain sometimes. :)

      • http://melissa-brandon.com Brandon Hansen

        I totally understand (and figured that was probably what was going on). Those are a nightmare at times.

      • http://ramaboo.com david

        Years ago I wrote a code processing script for highlighting plugins. I will have to see if I can find it again. It escaped html characters like greater than less than and padded tabs with nbsp;

  • http://michael.theirwinfamily.net Michael

    Great list! I haven’t used the output buffering much, but I might have to look into using that. Thanks for the tut!

  • http://www.secretspedia.com/ Waseem

    this is an amazing post , I need this to improve my skills in PHP
    Thanks a lot

  • Emil

    Great to see that you incorporate those rebuttals! Collective minds beat single minds every day of the week.

  • http://www.jonrawlins.co.uk Jon Rawlins

    Saving this for future reference, as it’s tutorials like this that I need to gain the knowledge I require in PHP. Thanks for such a good informative article for which I will be using from now on to learn the aspects of PHP.

  • http://james.padolsey.com James

    I think your DRY example is lacking. As far as I’m concerned true DRYness can only be achieved through sufficient abstraction and well-thought coupling. It’s not as simple “assign a string to a variable”…

    • http://vasili.duove.com/ Vasili

      Yeah. I was kinda disappointed to see the example for DRY. A good example for DRY would have been a parent class with classes extending that parent class…

  • http://nickd.info Nick D

    What’s it going to be with #14?

    You state one thing, then IMMEDIATELY after that, state the complete opposite.

    And is there a source for that rebuttal?

    • http://www.jeff-way.com Jeffrey Way

      Glen stated one thing. I stated another. My source is the PHP dev team.

      • http://www.jeff-way.com Jeffrey Way

        Everyone – just to clarify – If it says “Rebuttal,” it’s me writing. Otherwise, it’s Glen. :)

      • http://craigballinger.com Craig Ballinger

        Is your single quotes vs double quotes rebuttal source documented anywhere? Almost every reference I’ve found to the single quotes vs double quotes argument says exactly the opposite. Definitely want to be aware of it if it’s true. So much misinformation online.

      • http://vasili.duove.com/ Vasili

        I’m with Craig on this one. I’ve heard that you should use single quotes for almost everything and then double quotes when you’re using a variable inside that string. Maybe it’s a typo?

      • http://craigballinger.com Craig Ballinger

        This is my understanding of it:

        $years = 26;

        ‘I am $num years old’; //doesn’t work
        “I am $num years old’; //works as expected, but slower
        ‘I am ‘.$num.’ years old’; //best practice

        We’re not talking huge amounts of time here, from what I’m seen/tested we’re looking at about 5 seconds difference in 1 million iterations.

        I guess the key in your rebuttal could be “without variables”.

        $age = ‘I am 26 years old’;
        $age = “I am 26 years old”; //faster? seems counter-intuitive, but possible

      • http://craigballinger.com Craig Ballinger

        Previous comment was a train wreck. Can’t update comments here?

        should be:

        $num = 26;

        “I am $num years old”; //works as expected, but slower

      • Toby

        It might also be worth noting that there are different measures of efficiency. The implication here is that we’re all after shaving a millisecond off parse time. I use single quotes mainly to improve readability (because I can’t stand escaping double quotes in chunks of html, which then becomes an unreadable mess).

      • http://melissa-brandon.com Brandon Hansen

        This is a pretty solid guide right here- http://code.google.com/speed/articles/optimizing-php.html

    • Jeff

      Actually, it’s not. There are a bunch of errors in that Google article.

  • Deoxys

    lol, these are 32 practices, not 30 ;-)

    • http://www.jeff-way.com Jeffrey Way

      Sorry – I’m a bit slow this morning. How so?

      • Deoxys

        … 17, 18, 19, 18, 19, 20, …
        That so!
        And, by the way regarding point 29. The app is called Strace, not Stace ;-)

    • Aqib

      lol, thats funny.

  • http://fwebde.com/ Eric B.

    Thanks for the tips! I’ll be sure to try out the output buffering!

  • sven

    excellent post!

  • http://furoma.com Rohan

    Lol.. 17,18,17,18. How is that correct? Nice article though.

  • Arnold

    nice post again..
    bookmark

    best IDE for me right now is netbeans

  • http://www.newarts.at Drazen Mokic

    Good practices, but i cant aggree with #27, in no point.

    1.

    Like Jeffrey edited its not quicker and the script can get only slower with that practice. Imagine you have to use a variable a few times in your script, then its more code when you do things like

    if (mysql_real_escape_string(trim($_POST['username'])) == ‘test’ ) …
    {
    echo mysql_real_escape_string(trim($_POST['username']) …
    }

    less code would be

    $username = mysql_real_escpae_string(trim($_POST['username']));

    if ($username == ‘test’)
    {
    echo $username
    }

    2. I don’t think its cleaner but that may depend on the coder

    • Net

      You have your point, he had his point.
      Use once, he’s right. Use twice, you’re right.

      :)

  • Declan Dowling

    Pretty good stuff, covers a lot of the things I needed clarification on when starting to code.
    The caching info is something I think alot of new coders will find useful.
    Aalso “16. Never, Ever Trust Your Users” = lol. Assuming everyone is trying to sql inject is good :).

    @ 14. Know the Difference Between Single and Double Quotes:
    It would be good to show a few examples here I think, of when double quotes are and aren’t needed.

    @ 17. Store Passwords with Encryption:
    Its right to include this. However even though Jeff added his Rebuttal to it, I don’t see the need for using md5 even with a salt when there is the much easier alternative of a simple sha1 hash.

    @ 27. Don’t Copy Extra Variables:
    I was gonna comment, but Jeffs your rebuttle basically covered it.

    Overall a good resource, as expected from Nettuts.

    • Declan Dowling

      I spelt rebuttal wrong the second time – lol.

  • http://www.pixmatstudios.com demogar

    Great post :)

    I use Navicat for DB design, they have a Free version and it’s really great.

    • http://www.newarts.at Drazen Mokic

      Hm, Navicat looks nice. I guess i will try it for some days, thank you!

    • Net

      looks like dbvisualizer still sit in front

  • Sezain

    4. Try a PHP Framework

    You can learn a lot about PHP just by experimenting with PHP frameworks. Frameworks like CakePHP or CodeIgniter…

    AND

    13. Use Objects (or OOP)

    IS

    non-connected!

  • http://www.arteki.com Gaby

    I just put ob_start() onto my site, and wow what a different! I had started to get annoyed with everything getting loaded in turn because the main content was backgroundless until the sidebar loaded.

    Thanks so much for all these tips!

  • http://cmstutorials.org krike

    awesome :D I never knew there was a program to check if you have redundant code :D thanks a lot, really usefull.

  • http://youfailed.us jim d

    So if I’m not supposed to use the old-style scriptlet tags, how do I do something like .. do I really have to do ? That seems way more cumbersome. And in fact zend framework discourages the latter.

  • Jack F

    You’ve got a couple of extra items ;) If you check it actually goes 17, 18, 19 then the next point is 18 again ;)

    But awesome list, none the less, I’m just being fussy :P

    Thanks!

  • http://www.antsmagazine.com Nahid

    Wow! Lovely! Appreciate your hard work… I have bookmarked it!

  • Sebbe

    I disagree with using mamp/wamp now that Zend Server is here. Just to state what I mean: Zend Server just got updated with a new release so they have the new apache and php 5.3 (only on Community Edition (the one wich are free) but mamp haven’t been updated since late 2008. Well wamp is updated, but how sure can a person be that it it will be updated to the newest php version etc? With Zend they can be pretty sure, with others not so sure (my meaning).

    Thats allso the reason I choiced to start learning Zend Framework. And because of a book I bougth ^^

    -Sebbe

    • http://www.newarts.at Drazen Mokic

      I am using XAMPP and its so easy to configure on windows os taht i dont care if there are updates or not. In production mode i use anyway linux based servers.

      I dont like Zend, its so overpowered :D

    • http://www.brianswebdesign.com Brian Temecula

      One thing that I like about Wampserver is that I was able to install a security certificate so that I can fully test my site. The only thing that I don’t have functional on my Wampserver is email.

      It really doesn’t matter what server you use. I think the act of having a server to test on that is like the production server is all that is required.

  • Mad

    Great post, just a remark :

    @16 has security breach under certain condition : if your script is called with extra “login=true” parameter (ex: index.php?login=true), the forward_to_secure_environment() function will be called because $login wasn’t initialized to false before the correct_user(x,x) function.

    • Darren

      I agree that the first line of that example should have been:

      $login = false;

      But I don’t understand how $_GET['login'] will be automatically assigned to the variable $login in your explanation? If you’re using some sort of framework that automatically assigns query string variables to local variables, there’ll be security holes everywhere and that would be a very bad idea.

      • Andrew Steenbuck

        This is only true is you have ‘register_globals’ set to true in your ini file. This can be a big security problem if you have it enabled, which is why many hosts disable it. Its deprecated in 5.3 and won’t be an option in 6 (http://us2.php.net/manual/en/security.globals.php)

  • Matthijn

    What is zo ‘DRY’ on point 5? Imho DRY is more like, trying to make the classes and functions so you can reuse them.

    For an example, if you have two functions who are allmost alike, exept for the last line, try to make it one function, because when there is an error in the first function, there is most likeley to be the same error in the second, that way, you will have to deal with both, if you can combine it in a single function, you only have to worry about that one.

  • Matthijn

    Where is the freakin edit button, point 8:

    Allways use well the point is intended, you should not ever never use short tags, but the ending tag of ?> can be ommitted and is fully valid and working on all server configurations, it allso gives some neat advantages.

    No accidental whitespace after the ?>, how many times has there been header errors because output has been send, and you didnt know why? Mostly it is because some output was send, for example a whitespace or enter before the

    Ommiting the ?> makes sure you dont have whitespace after your php, (ofcourse this only works when you only have a single opening tag, and dont have some html mixed in your php by opening and closing php (which is a bad practice, html en php (logic) should be seperated (MVC)).

    The other advantage is, its less code, not much, but less nevertheless.

  • http://chrisberthe.com/ chrisberthe

    Cool list, didn’t know of the database visualizer :) Thanks.

  • hash

    For anyone wondering about the performance issues mentioned above, Geff is correct (if you believe the guys that actually write the php engine). Their comments on googles article can be found here

    http://groups.google.com/group/make-the-web-faster/browse_thread/thread/ddfbe82dd80408cc

  • http://lukeszanto.info Luke

    With number 4, I wouldn’t ever tell a beginner to learn a framework. It means that they will simply learn to rely on the syntax of the framework. Instead you should get a good handle of the language and how things work before trying to take short cuts.

  • http://horuskol.net HorusKol

    Nice post – plenty of good advice in there…

    #1 – just can’t be stressed enough – I’ve lost count of the times where people just don’t RTFM…

    #2 – I’d turn on E_STRICT as well ( by stating E_ALL | E_STRICT ) – that way, you get warnings when you use deprecated code

    #27 – hmm… not the best example, really – and there are plenty of times where you would want to ‘copy extra variables’ for easy reading – for example, you know that $_POST and $_GET and $_COOKIE are raw inputs that may be dangerous – copy the validated indexes from the arrays in a new array called $clean so you know that validation has been done…

    #28 – definitely should be using a version of PHP5 wherever possible – but you should develop on the same version of PHP which is on your host or production server – no point developing PHP 5.3 when your host is using 5.2.6 as you’ll likely find functions/functionality missing.

  • http://tuvidaloca.net Rata

    Nice.
    Short by points.
    Pushy ;)

    Thanks.

    Kind regards
    Rata

  • http://blog.insicdesigns.com insic

    How I wish our Internal Tech read this article especially #28. Coz I’ve been requesting a lot of time to upgrade the PHP version :)

    Very nice article by the way.

  • http://fahri-blog.site90.com fahri

    great list, i have to try myself this tricks….
    thanks for sharing…..

  • benaissa

    many thanks, very helpful best practices

  • Peter

    Another fairly long comment. Sorry folks for making your scroll past these. :)

    Befriend the PHP Manual
    Whilst the manual is an awesome resource, if you are super-new to PHP then it can be a daunting document to wade through. There are various sections for many levels of PHP author from introducing the syntax of the language, through to the technical documentation of much of the language. Also, the manual is constantly evolving and has a dedicated team of volunteers working to keep it up-to-date with advances in PHP and to make changes to existing documentation for any of a variety of reasons. Bugs, issues, errors, problems with the manual can be submitted to the bug tracker just like any other bug (like with PHP itself) at http://bugs.php.net/

    Turn on Error Reporting
    During development, absolutely turn on error reporting to the fullest level that you can. I would suggest error_reporting(E_ALL | E_STRICT) (with PHP 5) to cover as much as possible. Also, make sure that the display_errors setting is enabled.

    Try an IDE
    I think it’s right to point out here that IDEs are not for everyone; some people just prefer much simpler editor software to get the job done (usually alongside separate software for other tasks an IDE might roll into one).

    Always use (full PHP tags)
    To correct the article, to the best of my knowledge (though do feel free to correct me) none of those methods are deprecated (or depreciated) nor unofficial. However, the advice is to always use the full PHP tags.

    Comment, Comment, Comment
    One thing that I often see beginners do, when they’re trying to be nice and helpful to anyone looking over their code (including themselves) in the future is to make unnecessary comments. A common mistake is to comment what the code does when it is already very clear, like “// loops over the array of fruits” preceeding a foreach loop!

    Give your Scripts Limits
    Mention is made of set_time_limit, perhaps also mention or link through to other useful options; max_execution_time, max_input_time, post_max_size, (the latter few are useful for file uploads in particular) etc..

    Use OOP
    Perhaps also link through to the OOP manual pages for people wishing to learn the details of objects and their syntax in PHP.

    Know the Difference Between Single and Double Quotes
    Rather than making reference to any (debated and really not significant) performance differences between the two; the main difference (which is obvious to anyone except beginners) is that single quotes do not allow variables inside and double quotes do. This is what all beginners must be introduced to, but more and more (especially recently) the first thing people are introduced to on this topic is “use single quotes because they’re faster” (usually followed by shouts of “hey, no!”).

    Store Passwords with Encryption
    The rebuttal states that MD5 has been compromised without suggesting any alternative. There are many other hash algorithms considered more secure than MD5, a popular alternative is SHA-1. See the hash functions reference for that and others.

    Validate Cookie Data
    Cookie data can be considered harmful, it is user input just like any other. However, why on earth would one use htmlspecialchars() or mysql_real_escape_string() to validate that input? The filter extension provides a number of useful ways to sanitize and/or validate any user input. Those functions mentioned in the article do absolutely nothing towards validating the cookie input.

    Keep Functions Outside of Loops
    You take a hit of performance whenever a function is called, not just within loops. This hit is just multiplied by the number of times the loop is run (assuming the function is called each time). I think this paragraph of the article may be confusing for beginners especially, a code snippet of bad and then good wouldn’t go amiss.

    Don’t Copy Extra Variables
    Sure, if a variable would only be used once and if not using it doesn’t adversely affect the clarity of the code then by all means don’t use one! However even if the variable is only used twice it may well be more clear to use it than, for example, make the same function call multiple times.

    Upgrade to the Latest Version of PHP
    At the time of writing, the latest stable versions are PHP 5.3.0 and 5.2.10.

    That’ll do for now!

  • http://eduardosasso.com Eduardo Sasso

    Nice compilation, very helpful for any level of programmer.

  • http://jashsayani.com Jash Sayani

    Bookmarked!

    I have to create a script to fetch all posts by Jeremy Buff on ThemeForest and NetTuts and bookmark them on my Delicious account. Automation :)

    • http://jashsayani.com Jash Sayani

      Sorry, I meant Jeffrey Way. I really get confused with names these days. Too much coffee is bad!

  • http://www.prospectwire.com adam16ster

    So I should use a framework..ok..i’ll choose codeigniter.
    I should also use an ide..ok..i’ll choose netbeans.
    I need a blog and other stuff so I need a CMS..ok..i’ll choose wordpress.

    My question is how on earth do you get all these tools to work together in harmony? Is it possible? Does any combination of ide,framework, and cms play nice together? Will I get code completion and debugging for codeigniter in netbeans? Then can I get codeigniter in wordpress without hacking away at core files?

  • Hans-Kristian

    #25: “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.”

    Using a template system is definitely not going to increase the performance of an application. It will actually decrease it. At some time the template tags have to be converted into PHP and it will never be faster than using plain PHP (alternative syntax is nice for templates), which in addition is far more flexible. One should rather consider an opcode cache.

  • http://www.twitter.com/mujeebkhumawala Mujeeb Khumawala

    This is simply awesome list of Best Practices for PHPiers. It only comes after a sheer experience.

    Thanks for sharing. I would say – A must Bookmark post.

  • http://www.webhostright.com/ Webhostright

    Thanks, its very useful advice and info for myself.

  • http://www.webhostdesignpost.com/webhosting/top10webhosting.html Cody

    Very nice “Practices,” even for people that aren’t Beginners.

  • http://www.weareplic.com Devan

    Use MYSQLI instead of mysql.

  • http://www.visual-blade.com Daquan Wright

    Learn how to program while you’re learning PHP or any other language for that matter is my tip. ;)

    Nice article.

  • http://aaqil.tk Pakistani

    Thank you for spreading the knowledge :)

  • http://www.esvon.com/ Vladimir

    Thanks for good tips, I’m thinking about Zend Platform to be a valuable addition to profiling tools (free for developers, but have to try it to be sure)

  • http://www.xemmex.com XemmeX

    Cool! I will keep this as reference for my employee! LOL Super tut!

  • http://mahmoudkamal.com mahmoud kamal

    good Job

  • Tony Schizoid

    Please stop writing (and saying, for that matter!) “If you’re wanting to…”.

    The correct grammar is “If you want to…”.

    “Want” is a stative verb, and as such is rarely used in progressive forms.

    I hope your English language skills are not a reflection of your PHP (and general web programming) skills!