While PHP continues to be one of the most prolific programming languages used across the web, it has been active for over 20 years now and has consequently developed its share of quirks, bugs, and most of all outdated methodologies easily found when Googling for a particular answer.
Determining your own PHP best practices can be daunting given the abundance of information that has accumulated on the web over the years. To help you sort through the clutter and get to the most up-to-date information, we’ve outlined some of the key components of most web applications and highlighted the PHP example code within each to get you started down the right track.
Sending email is, of course, an incredibly important task that nearly every web project will need to be capable of, but unfortunately, the default mail() function in PHP is objectively lacking and insecure.
Thankfully, there is a great open-source project called PHPMailer that is capable of everything you’ll ever need for email and is trusted by a great number of open-source projects including WordPress, Drupal, and Joomla.
Using the class is very simple and involves creating a new instance of the PHPMailer class, then modifying the settings via the user-friendly methods therein. Below is a tutorial example from the project site itself.
Working With Databases
With the release of PHP 5.1, developers now have a more reliable and secure method for connecting to and querying databases, using PHP Data Objects (PDO). Unlike past methods of working with databases, the PDO interface provides an abstraction layer, allowing you to use the same functions and methods regardless of the specific database you’re using. This greatly simplifies development across projects or even within the same codebase when multiple databases or data engines are in use.
For developers coming from newer languages, such as Ruby on Rails, this abstraction will seem very familiar. Utilizing the PDO interface is a good practice to get into due to the extra security and simplicity it provides.
Handling Dates & Times
While PHP still contains a plethora of functions aimed at dealing with dates and times, thankfully a lot of the pain of PHP development in the past has been reduced with PHP 5.2 and the introduction of the DateTime class.
DateTime can do everything you’ll need in a simple, object-oriented fashion from comparisons and calculations to modification and even time zone management.
Generating Secure Password Hashes
PHP 5.5 introduced a simple and secure method for handling password hashing and verification via password_hash() and password_verify(), respectively. With these functions, you can easily generate a secure hash using the most secure algorithm available to PHP. By utilizing the PASSWORD_DEFAULT option, your code will take advantage of whatever current encryption algorithm is considered most secure in that version of PHP, so there’s no need to worry about future-proofing.
These functions also automatically generate random cryptographic salt, thus, while you can pass your own salt if you wish, it’s strongly recommended you allow the default function to add salt itself.
While you can certainly create your own fancy regular expression tests to validate common strings such as an email address, URL, or IP address, it is much simpler to rely on the built-in capabilities of the filter_var() function instead. By passing the appropriate FILTER_ constant, you can easily validate a wide assortment of input values with only a single line of code.
Filtering User Input
It is vital for any project that accepts user input to properly screen and sanitize that data before executing upon it in your own code, to prevent malicious attacks or simple user entry errors. In addition to filter_var() illustrated above, PHP 5.2 also introduced the very useful filter_input() function, allowing you to easily retrieve an external variable — from global sources like $_GET and $_POST — and then filter that data as necessary.
In the example below, we have a simple test to illustrate how filter_input() can be used to sanitize user data (in this case values in the query string) to ensure the information is of the appropriate type the application expects.
Counting Looped Arrays
Frequently, you’ll want to determine the size of an array in order to loop through the values and execute some code. A simple but hugely impactful practice is ensuring you determine and store the size of your array before looping begins. This is particularly true when working with global variables. Even in simple examples as illustrated below, with an array of size 10,000, calculating the size in advance reduces execution time by 600,000%!
This is just one (extreme) example of why it’s wise to get in the habit of defining variables beforehand whenever possible.
Using Regular Expressions
With PHP 5.3, the POSIX Regex extension — one of the two regex extensions available in modern PHP — has been deprecated in favor of Perl-compatible regex (PCRE). There are a few reasons, but the primary concern leading to this standard switch is that PCRE is typically faster due to the default behavior of searching for the first available match rather than the longest length match.
Be sure to use only PCRE functions (preg_*) for all your PHP regex needs. Below is a simple example of checking for a whole word within a longer sentence.
Interested in mastering the PHP stack in just four weeks? Check out Coding Dojo’s LAMP Dev Accelerator Program (offered onsite and online), which covers the full PHP stack, including the most important elements of utilizing the Apache web server, MySQL database and PHP.