PHP Security Guide: How to save your PHP website?

Advance Idea Infotech
May 7 · 11 min read

Damn, but security is hard. It’s not always obvious what needs doing, and the payoffs of good security are at best obscure.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.

This security checklist aims to give developers a list of PHP security best practices they can follow to help improve the security of their code.

Table of Content

  1. Security Issues in PHP CMS
  2. What This PHP Security Tutorial Contains?
  3. Update PHP Regularly
  4. Set open_basedir
  5. Cross-site scripting (XSS)
  6. SQL Injection Attacks
  7. Cross site request forgery XSRF/CSRF
  8. Session Hijacking
  9. Hide Files from the Browser
  10. Securely Upload Files
  11. Use SSL Certificates For HTTPS
  12. Deploy PHP Apps on Clouds
  13. Document Root Setup
  14. Log all Errors and Hide in Production
  15. Do not send sensitive information in&headers
  16. Wrapping Up!

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

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

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?

  • 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

Update PHP Regularly

If you are using PHPStorm then you can use PHP 7 Compatibility Inspection, that will show you which code will cause you issues.

Set open_basedir

Read more:

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

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

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:

Securely Upload Files

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.

Deploy PHP Apps on Clouds

They are fast, safe and secure for any kind of website and application. They always provide secured layer to prevent DDOS, Brute force and phishing attacks which are highly detrimental for web applications.

To deploy your PHP project on cloud servers, you must have good Linux skills to create powerful web stacks like LAMP or LEMP, which often costs you time and budget for Linux professionals. Instead, Advance Idea Infotech managed PHP and MySQL hosting platform provides you the easy way to deploy servers with Thunderstack within few clicks on the above-mentioned cloud providers.

The Thunderstack helps your PHP application to be completely secured from various malicious attacks and guarantees optimized performance.

Document Root Setup

/public serves the output of application similar to simple PHP website with index.php file. The purpose to set the webroot to var/www/html/public is to hide the sensitive files like .htaccess and .env which contain the environment javariables and credentials of database, mail, payment APIs.

Also, frameworks like Laravel, Symfony recommend to not move all of your files to root folder, instead creating a nice directory structure to save related files like view, models and controllers is a more reasonable approach.

Log all Errors and Hide in Production

Now, after making display off, log all the errors to a specific file for future needs:

Obviously, you can change file name as you want.

Do not send sensitive information in headers

Read more:

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. In this article, we have covered basic PHP security issues, to help you understand how to secure your PHP projects from different malicious attacks. We’ll also write about few more PHP security tips and tricks in the future as well.

Advance Idea Infotech

Written by

Advance Idea Infotech is an web development outsourcing company & Mobile App Development company in India providing information technology services