Ultimate PHP Security Best Practices

Ultimate PHP Security Best Practices

Securing web applications from all sorts of forged attacking attempts is the ultimate duty of a web developer. You should build your web apps protective enough to have no security issues or loopholes, thus eradicating the possibility of any malicious attack. In most cases, the developers must take the responsibility and put in every possible effort to identify the vulnerabilities and propose solutions, if any to address the issues prevailing in the apps.

PHP is a popular language for web development. It is so popular that In some cases companies do run few bounty programs in which they invite different security experts to analyze their application from the core and suggest critical PHP security best practices for it.
PHP is the most criticized scripting language when it comes to security. A major chunk of developers and QA experts think PHP has no robust techniques to secure applications. The verdict has some ground too because PHP is the oldest and widely used language for web app development. But for a long time since PHP 5.6, we haven’t seen any major updates regarding security and hence the language faces some security issues.

Security Issues in PHP CMS

Popular CMS like WordPress, Joomla, Magento, and Drupal are built in PHP and according to Sucuri, most of the vulnerabilities in PHP CMS came to light during the year 2017:
  • WordPress security issues rose from 74% in 2016 Q3 to 83% in 2017.
  • Joomla security issues have dropped from 17% in 2016 Q3 to 13.1% in 2017.
  • Magento security issues rose marginally from 6% in Q3 2016 to 6.5% in 2017.
  • Drupal security issues dropped slightly from 2% in Q3 2016 to 1.6% in 2017.
cms infection comparison
The current situation is not good enough, but thanks to open source contributors, who are trying hard to overcome the problems and we have seen some drastic changes in PHP of late. PHP 7.x was launched last year with various updates and fixes. The best thing about PHP 7.x relates to the security upgradations which truly revamped the security protocol of the language.

What This PHP Security Tutorial Contains?

I’ve been working on PHP security and performance issues for a very long time, being highly active in the PHP community asking top developers about the tips and tricks they are using in their live projects. Therefore, the main aim of this PHP security tutorial is to make you aware about the best practices for security in PHP web applications. I will be defining the the following problems and mentioning possible solutions for them.
  • Update PHP Regularly
  • Cross site scripting (XSS)
  • SQL Injection Attacks
  • Cross site request forgery XSRF/CSRF
  • Session Hijacking
  • Hide Files from the Browser
  • Securely Upload Files
  • Use SSL Certificates For HTTPs
  • Deploy PHP Apps on Clouds
Note: please do not consider it as a complete cheat sheet. There must be better ways and more unique solutions developers would be applying on the their applications to make it perfectly secured.

Update PHP Regularly

Right now, the most stable and latest version of PHP available is PHP 7.2.8. I recommend that you must update your PHP application to this new one. If you are still using PHP 5.6 then you will be having a lot of deprecations while upgrading PHP apps. You will also need to update your code and change some functional logics like password hashing etc. There are also some tools available to check the deprecation of your code and help you in migrating those. I have listed some tools below:
  1. PHP 7 Compatibility Checker
  2. PHP 7 MAR
  3. Phan
If you are using PHPStorm then you can use PHP 7 Compatibility Inspection, that will show you which code will cause you issues.

Cross-site scripting (XSS)

Cross site scripting is a type of malicious web attack in which an external script is injected into the website’s code or output. The attacker can send infected code to the end user while browser can not identify it as a trusted script. This attack occurs mostly on the places where user has the ability to input and submit data. The attack can access cookies, sessions and other sensitive information about the browser. Let’s look at the example of a GET request which is sending some data through URL:
You can figure out this attack by using htmlspecialchars. Also by using ENT_QUOTES, you can escape single and double quotes.
Meanwhile, XSS attacks can also execute via attributes, encoded URI schemes and code encoding.

SQL Injection Attacks

The SQL injection is the most common attack in PHP scripting. A single query can compromise the whole application. In SQL injection attack, the attacker tries to alter the data you are passing via queries. Suppose you are directly processing user data in SQL queries, and suddenly, an anonymous attacker secretly uses different characters to bypass it. See the below-mentioned SQL query:
The $username can contain altered data which can damage the database including deleting the whole database in the blink of an eye. So, what’s the solution? PDO. I recommend that you always use prepared statements. PDO helps you in securing SQL queries.
Let’s look at another example in which GET data is sent through URL: http://example.com/get-user.php?id=1 OR id=2;
The connection between the database and application is made with the below statement:
You can select username based on the above ID but wait! Here SQL code ‘GET data’ gets injected in your query. Be careful to avoid such coding and use prepared statements instead:
Now you can avoid the above SQL injection possibility by using
Also, a good practice is to use ORM like doctrine or eloquent, as there is the least possibility of injecting SQL queries in them.

Cross site request forgery XSRF/CSRF

The CSRF attack is quite different to XSS attacks. In CSRF attack, the end user can perform unwanted actions on the authenticated websites and can transfer malicious commands to the site to execute any undesirable action. CSRF can’t read the request data and mostly targets the state changing request  by sending any link or altered data in HTML tags. It can force the user to perform state changing requests like transferring funds, changing their email addresses etc. Let’s see this URL in which GET requests is sending money to another account:
Now if someone wants to exploit the web application he/she will change the URL with name and amount like this
Now this URL can be sent via email in any file, Image etc and the attacker might ask you to download the
file or click on the image. And as soon as you do that, you instantly end up with sending huge amount of money you never know about.

Session Hijacking

Session hijacking is a particular type of malicious web attack in which the attacker secretly steals the session ID of the user. That session ID is sent to the server where the associated $_SESSION array validates its storage in the stack and grants access to the application. Session hijacking is possible through an XSS attack or when someone gains access to the folder on a server where the session data is stored.
To prevent session hijacking always bind sessions to your IP address to:
Watch for it when working on localhost as it doesn’t provide you the exact IP but :::1 or :::127 type values. You should invalidate (unset cookie, unset session storage, remove traces) session quickly whenever a violation occurs and should always try not to expose IDs under any circumstances.
for  cookies, the best practice is to never use serialize data stored in a cookie. Hackers can manipulate cookies easily, resulting in adding variables to your scope. Safely delete the cookies like this:
The first line of the code ensures that cookie expires in browser, the second line depicts the standard way of removing a cookie (thus you can’t store false in a cookie). The third line removes the cookie from your script.

Hide Files from the Browser

If you have used micro-frameworks of PHP, then you must have seen the specific directory structure which ensures the placement of files properly. Frameworks allow to have different files like controllers, models, configuration file(.yaml) etc in that directory, but most of the time browser doesn’t process all the files, yet they are available to see in the browser. To resolve this issue, you must not place your files in the root directory but in a public folder so that they are not accessible all the time in browser. Look at the directory structure of the Slim framework below:
slim directory structure

Securely Upload Files

File uploading is a necessary part of any user data processing application. But remember at some points, files are also used for XSS attacks as I have already explained above in the article. Returning to the basics, always use the POST request in the form and declare the property enctype=”multipart/form-data” in <form> tag. Then validate the file type using finfo class like this:
Developers can create their own custom and ultra-secure file validation rules, but some frameworks like Laravel, Symfony and codeigniter already have pre-defined methods to validate file types.
Let’s look at another example. The HTML of form should be like this:
And upload.php contains the following code:
Properly declaring the UPLOAD_ERR and basename() may prevent directory traversal attacks, but few other validations – like file size, file rename and store uploaded files in private location – are also required to strengthen the security of the applications.

Use SSL Certificates For HTTPS

All the modern browsers like Google Chrome, Opera, Firefox and others, recommend to use HTTPS protocol for web applications. HTTPs provides a secured and encrypted accessing channel for untrusted sites. You must include HTTPS by installing SSL certificate into your website. It also strengthens your web applications against XSS attacks and prevents the hackers to read transported data using codes. Cloudways provides free SSL certificates on one-click which are valid for 90 days and you can easily revoke or renew them with a click. You can follow the guides for setting-up SSL Certificates in your PHP, WordPress, Magento and Drupal applications.

Wrapping Up!

Well, The PHP security best practices is a very vast topic. Developers from around the world tend to develop different use cases to secure web apps. While many companies run different bounty programs to find out security loopholes and vulnerabilities in their applications and thus reward those security experts who point out critical loopholes in the applications. In this article, I have covered basic PHP security issues, to help you understand how to secure your PHP projects from different malicious attacks. I’ll also write about few more PHP security tips and tricks in the future as well. Till then you can contribute your thoughts and security practices in the comments section below.