PHP Best Practices

Compatibility

Turn on Error Reporting for Development
Development and Staging environment differs from a production environment in many aspects. We should not display server and script errors on a production environment. That is risky for security, since the insides, data-schema and weak points could be studied by an outsider.

But for development and staging, developers should be able to see the errors in order to easily identify them and fix them.

Never Use Short Tags
Short php tags is a deprecated feature. It can cause unexpected results. Most of all, it can mix-up with XML Declaration and confuse the web-server. When this feature is enabled, it is hard (though not impossible) to generate XML Declaration for XML outputs. Codes not working after deploying or server updating/upgrading is another downside.

Don’t use Magic Quotes
Just like Short tags, using this deprecated feature may allow writing code that wouldn’t work after deploying or may break up-on server updates/upgrades.

Use Meaningful Variable and Function Names in your Code.

Consistent Naming Scheme
This is especially important when developing on Windows for Linux environments. Most of the web apps/sites are hosted on a Linux environment where file names upper-case/lower-case do matter.

File and Folder Organization

Readability

Maintaining a Proper Coding Standard
Large projects need collaboration. A proper code standard is a key requirement for many people to work on one project.

Indentation & Consistent Indentation
Proper indentation makes code more readable. A key reason for errors and hours of frustration is inconsistent indentation. Proper indentation not only makes code elegant, it prevents making errors – saving hours of development time.

Code Grouping
Just like indentation – leaving a little space between code blocks makes code more readable.

Capitalize SQL Special Words
SELECT, UPDATE, WHERE, FROM are better be written in all caps. Though it would still work in lower case, making these all caps makes it easier to read the code.

Refactoring (DRY Principle)
Refactoring makes the code simpler by grouping same functionality to functions – that can be reused. Code reusing makes code simpler and more readable.

The next step of refactoring is modularization, where we group similar functions to modules. There is yet another step to group functionality into libraries, which can be re-used for other projects, or can be imported from another project. For popular frameworks, there are libraries that can be downloaded or bought off-the-shelf to expand the functionalities.

A code that can be refactored but not refactored is a mess. Refactoring is a part of cleaning and tidying up, that makes it easier to manage and debug.

Let’s say we need to make a change to a functionality of an un-refactored code. It may require making the change in several places. On a refactored and modularized code, we may only have to make that change in one place.

Documentation

Commenting & Documentation, Avoid Obvious Comments
Some code does explain itself, and some code does not. Using descriptive variable, function names reduces the need for extensive inline documentation, but does never completely remove the need for documentation.

Minimal inline documentation is to explain every function, module on the top of it. As the complexity of a function increases, those may require more explanation.

Try a PHP Framework
Time spent for getting used to a framework is time well spent. Good frameworks save hours of development time in the end. Frameworks make development easy and faster.

Security

Filter all the input data before passing to the database, Protect your Script From SQL Injection SQL injection is a serious security threat. A simple example would be:

$db->query("SELECT id from `user`
    WHERE username = '$username' AND password = '$password'")

A hacker could enter the password as “nothing’ OR ‘true”, which will fetch the ID of the first user, probably of the admin. By sanitizing form inputs and/or with SQL injection protection libraries, we must prevent these types of vulnerabilities.

Encrypting Credit card details and Hashing Passwords
There is probably no system that is completely secure. It is a matter of time until hackers find a way to get into a system. And when they get in, the first thing they capture is Credit Card information and Passwords. Chances are high that some users use the same password everywhere. We cannot stop that. It is our responsibility to obfuscate their passwords.

Passwords must be hashed – it is like a one way encoding. When a user needs to log in, we hash the password they enter and match with the already hashed password in the database.

Credit card information on the other hand needs to be decrypted. If in any case CC details need to be recorded, those have to be encrypted with a private key. The best way to prevent a CC contingency is to offload credit card information to a third party payment processing company, and only keep the last four digits for reference purposes.

Validate Cookie Data
Cookie or session hijacking is another common security threat. It is easier to store username, privilege level or security clearance level on a cookie. But these cookies can be modified by the user, or a hacker too. A cookie is better when its a token, or an arbitrary hashed character sequence where there is very slim space for speculation by trial and error. User record for the given token could be mapped on the server-side for user level or access permissions.

Data files storage and File upload
Some web apps/sites may have data file storage apart from the database. These files should be stored in a non-web accessible path, or protected by an .htaccess file.

Some sites may allow users to upload files. These files would have to be made web-accessible. But these folders must be script execution disabled. A hacker could upload a script and run it otherwise.

Do Not Ever Put phpinfo() in the Root Directory
Specific sensitive details about a web server are given on a phpinfo. If you need to call phpinfo on a website, make it available for logged in admin users only – in the admin section.

Turn Off error reporting in production
Revealing error messages on a production site is bad for security. Hackers and exploiters gain knowledge of the internals, variable names, database schema or even weak points by studying error messages.

Performance

  • Use a Caching System
  • Profile your Code
  • Separation of Code and Data
  • Avoid Deep Nesting
  • Use consistent Temporary Names
  • Object Oriented vs. Procedural
  • Never Use Functions inside Loops
  • Use Single Quotes around Array Indexes
  • Use single Quotes whenever possible – Double quoted string is parsed in php. That is why a variable inside a double quoted string is evaluated. But using double quotes for a long string makes the code slower.
  • Use an IDE