30+ PHP Best Practices for Beginners

* { box-sizing: border-box; } body {margin: 0;}*{box-sizing:border-box;}body{margin-top:0px;margin-right:0px;margin-bottom:0px;margin-left:0px;}

PHP is the most widely used language for server-side programming on the web. Here are 30+ best practices for beginners wanting to gain a firmer grasp of the fundamentals. We have also written posts like these for HTML, CSS, and JavaScript.

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 and Feature Rich Editor

The great thing about programming is that you can write your PHP code in Notepad, and it will still run properly on a server if written correctly. However, your productivity will take a hit if you don’t use a full-blown IDE or at least a feature-rich text editor.

IDEs (Integrated Development Environments) are helpful tools when you want great support for a particular language. Different languages come with their own IDEs like PhpStorm for PHP. They give you features like syntax highlighting, code completion, error warnings, and refactoring (reworking).

You can also use some general-purpose text editors for writing code. Visual Studio Code is an excellent example of an editor which offers a lot of great features for multiple languages by integrating with third-party extensions.

Visual Studio CodeVisual Studio CodeVisual Studio Code

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

However, my advice for you would be to first learn the basics of the language and then take a look at some smaller open-source projects to see how they write code and then move on to big projects.

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:

This code…

now with the DRY approach:

You can read more about the DRY programming principle on Artima and Wikipedia.

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 Pollock 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. Envato Tuts+ writer Jason Lengstorf has written an excellent article on how to tier your PHP applications for easier maintenance.

8. Always Use <?php ?>

Programmers often try to take shortcuts when declaring PHP. Here are a few common ones:

While these do save a few characters, all of these methods are depreciated and unofficial. Stick with the standard as it’s guaranteed to be supported in all future versions.

9. Use Meaningful, Consistent Naming Conventions

Naming 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 need 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 XAMPP/MAMP/WAMP

MySQL is the most popular type of database to use with PHP (though it’s not the only one). If you want to set up a local environment to develop and test your PHP applications on your computer, look into installing MAMP (Mac) or WampServer (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.

PHP XAMPPPHP XAMPPPHP XAMPP

You can also consider using XAMPP if you are looking for a cross-platform solution. It is currently the most popular PHP development environment.

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.

14. Don’t Put phpinfo() in Your Webroot

The phpinfo() function is a beautiful thing. By simply creating a PHP file that has <?php phpinfo(); ?> and dropping it onto the server 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.

15. 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:

You might also want to use different filter functions like filter_var() and filter_input() to sanitize and validate your data.

16. Store Passwords With Encryption

Many PHP beginners often plunk sensitive data like passwords into the database without applying any encryption. At the very least, you should consider using MD5 to encrypt passwords before you put them into the database.

However, you should consider using functions like password_hash() and password_verify() to store and authenticate passwords. See one of our tutorials on creating a login form in PHP to see them in action.

17. 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 MySQL Workbench to visually design your databases.

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

Want to compress the HTML as well? Simply replace ob_start() with ob_start('ob_gzhandler').

19. 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 either by using the mysqli_real_escape_string() or by using prepared statements.

Here’s an example of mysqli_real_escape_string() in action:

and a prepared statement:

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. It’s much safer and, notably, faster when executing multiple CRUD statements at once.

20. Try Object Relational Mapping (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 and ORM is built into PHP frameworks like CakePHP.

21. 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:

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

22. Use a Caching System

If you want a more robust caching system, there are a few caching scripts for PHP that might be more complete than the above example. For instance, Memcached provides a high-performance caching system for your dynamic websites.

You can also use built-in OPCache in PHP in order to improve performance by making sure that PHP does not have to load and parse scripts on each request.

23. Validate Cookie Data

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

24. 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 template system that has caching built into it. Twig is yet another option if you are looking for a template engine.

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

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

27. Keep Functions Outside of Loops

You take a performance hit when you include functions inside 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 the loop.

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!

28. 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 especially true in situations where you will use that variable only once.

For example, the following code snippet:

can be written into a single line like this:

29. 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 previous versions of PHP and PHP 8.

Upgrading your PHP version also has other benefits such as improved security and access to new features and functions to help you write better code.

30. Learn About Newer Features in PHP

Continuing from my last point, PHP is constantly updating and improving. Make sure you are up-to-date on the latest developments happening with the language. We now have many new functions in PHP 8 that did not exist in earlier versions, like str_contains() and str_starts_with(). There are also concepts like the yield keyword used in generator functions and anonymous or lambda functions in PHP.

Generators have been available since PHP 5.5, but generator delegation was implemented in PHP 7.0. Similarly, arrow functions, which are basically more concise lambda functions, were introduced in PHP 7.4.

31. Use DateTime Classes in PHP to Your Advantage

Working with date and time in PHP can be a nightmare due to time-zone issues, daylight savings, and many other factors. PHP has had a DateTime class since version 5.2. It makes working with date and time in PHP a whole lot easier compared to using functions like date(), date_timezone_set(), etc. Consider using this class whenever you are writing your code.

32. Follow Modern Practices to Make Your Code Secure

PHP has been constantly becoming more and more secure with newer releases. This means that what was common many years ago might no longer be the best way to do things. While this applies to all aspects of the language, it is particularly important for security.

You will probably come across some old tutorials that have not been updated in a long time and could be using MySQL functions for accessing the database. The original MySQL extension has now been replaced with MySQLi, and you also have the option to use prepared statements. The same thing goes for storing and verifying passwords using secure dedicated functions.

33. 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 Strace (Unix) and Process Explorer (Windows) that allow you to find redundant processes and how you might combine them.

34. 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, or StackOverflow to ask questions to more seasoned PHP developers.

The PHP website has a page on getting PHP help.

This post has been updated with contributions fromĀ Monty Shokeen. Monty is a full-stack developer who also loves to write tutorials, and to learn about new JavaScript libraries.

Leave a comment

Your email address will not be published.