30+ PHP Best Practices for Beginners


SUBMITTED BY: Guest

DATE: May 5, 2013, 10:08 a.m.

FORMAT: PHP

SIZE: 16.0 kB

HITS: 1190

  1. 1. Befriend the PHP Manual
  2. 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.
  3. 2. Turn on Error Reporting
  4. 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.
  5. 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.
  6. 3. Try an IDE
  7. 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
  8. syntax highlighting
  9. code completion
  10. error warnings
  11. refactoring (reworking)
  12. And many other features. There are plenty of great IDEs out there that support PHP.
  13. 4. Try a PHP Framework
  14. 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.).
  15. Rebuttal: I personally wouldn’t recommend that beginners use a framework. Learn the fundamentals first. :)
  16. 5. Learn the DRY Approach
  17. 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:
  18. This code…
  19. view plaincopy to clipboardprint?
  20. $mysql = mysql_connect('localhost', 'reinhold', 'secret_hash');
  21. mysql_select_db('wordpress') or die("cannot select DB");
  22. now with the DRY approach:
  23. view plaincopy to clipboardprint?
  24. $db_host = 'localhost';
  25. $db_user = 'reinhold';
  26. $db_password = 'secret_hash';
  27. $db_database = 'wordpress';
  28. $mysql = mysql_connect($db_host, $db_user, $db_password);
  29. mysql_select_db($db_database);
  30. You can read more about the DRY programming principle here and here.
  31. 6. Indent Code and Use White Space for Readability
  32. 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.
  33. 7. “Tier” your Code
  34. 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.
  35. 8. Always Use <?php ?>
  36. Often times programmers try to take shortcuts when declaring PHP. Here are a few common ones:
  37. view plaincopy to clipboardprint?
  38. <?
  39. echo "Hello world";
  40. ?>
  41. <?="Hello world"; ?>
  42. <% echo "Hello world"; %>
  43. 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.
  44. 9. Use Meaningful, Consistent Naming Conventions
  45. 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.
  46. 10. Comment, Comment, Comment
  47. 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.
  48. 11. Install MAMP/WAMP
  49. 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.
  50. 12. Give your Scripts Limits
  51. 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.
  52. 13. Use Objects (or OOP)
  53. 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.
  54. 14. Know the Difference Between Single and Double Quotes
  55. 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.
  56. 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.
  57. 15. Don’t Put phpinfo() in your Webroot
  58. Phpinfo is a beautiful thing. By simply creating a PHP file that has
  59. <?php phpinfo(); ?>
  60. 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.
  61. 16. Never, Ever Trust Your Users
  62. 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:
  63. view plaincopy to clipboardprint?
  64. <?php
  65. if (correct_user($_POST['user'], $_POST['password']) {
  66. $login = true;
  67. }
  68. if ($login) {
  69. forward_to_secure_environment();
  70. }
  71. ?>
  72. 17. Store Passwords with Encryption
  73. 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.
  74. view plaincopy to clipboardprint?
  75. echo md5('myPassword'); // renders - deb1536f480475f7d593219aa1afd74c
  76. 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.
  77. 18. Use Database Visualization Design Tools
  78. 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.
  79. 19. Use Output Buffering
  80. 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.
  81. To enable output buffering, simply add ob_start() like so at the top of the file.
  82. 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’)”;
  83. Refer to this Dev-tips article for more information.
  84. view plaincopy to clipboardprint?
  85. <!DOCTYPE html>
  86. <?php ob_start('ob_gzhandler'); ?>
  87. <html lang="en">
  88. <head>
  89. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  90. <title>untitled</title>
  91. </head>
  92. <body>
  93. </body>
  94. </html>
  95. <?php ob_end_flush(); ?>
  96. 20. Protect your Script From SQL Injection
  97. 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.
  98. Here’s an example of mysql_real_escape_string in action:
  99. view plaincopy to clipboardprint?
  100. $username = mysql_real_escape_string( $GET['username'] );
  101. and a prepared statement:
  102. view plaincopy to clipboardprint?
  103. $id = $_GET['id'];
  104. $statement = $connection->prepare( "SELECT * FROM tbl_members WHERE id = ?" );
  105. $statement->bind_param( "i", $id );
  106. $statement->execute();
  107. 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.
  108. Read more on creating secure PHP applications at Nettuts.
  109. 21. Try ORM
  110. 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.
  111. There are plenty of ORM libraries for PHP like Propel, and ORM is built into PHP frameworks like CakePHP.
  112. 22. Cache Database-Driven Pages
  113. 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:
  114. view plaincopy to clipboardprint?
  115. // TOP of your script
  116. $cachefile = 'cache/'.basename($_SERVER['SCRIPT_URI']);
  117. $cachetime = 120 * 60; // 2 hours
  118. // Serve from the cache if it is younger than $cachetime
  119. if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) {
  120. include($cachefile);
  121. echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->";
  122. exit;
  123. }
  124. ob_start(); // start the output buffer
  125. // Your normal PHP script and HTML content here
  126. // BOTTOM of your script
  127. $fp = fopen($cachefile, 'w'); // open the cache file for writing
  128. fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file
  129. fclose($fp); // close the file
  130. ob_end_flush(); // Send the output to the browser
  131. This bit of code will use a cached version of a page that is less than 2 hours old.
  132. 23. Use a Caching System
  133. 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.
  134. Memcached
  135. APC
  136. XCache
  137. Zend Cache
  138. eAccelerator
  139. 24. Validate Cookie Data
  140. 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().
  141. 25. Use Static File Caching Systems
  142. 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.
  143. 26. Profile your Code
  144. 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.
  145. 27. Code to a Standard
  146. 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.
  147. 28. Keep Functions Outside of Loops
  148. 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.
  149. 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. :)
  150. 29. Don’t Copy Extra Variables
  151. 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:
  152. Bad
  153. view plaincopy to clipboardprint?
  154. $description = strip_tags($_POST['description']);
  155. echo $description;
  156. Good
  157. view plaincopy to clipboardprint?
  158. echo strip_tags($_POST['description']);
  159. 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.
  160. 30. Upgrade to the Latest Version of PHP
  161. 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.
  162. 31. Reduce the Number of Database Queries
  163. 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.
  164. 32. Don’t be Afraid to Ask for Help
  165. 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.

comments powered by Disqus