PHP SECURITY: How to deal with common web vulnerabilities

PHP is arguably one of the big guns when it comes to web application development. It also powers highly popular CMSs such as Wordpress, Drupal, and Joomla, which means PHP security should be at the heart of the development community.
The sad reality, however, is that every single PHP application is prone to some form of attack. We can fill this security gap by understanding potential vulnerabilities and how to address the associated risks.
In this post, we’ll walk you through two of the most prevalent vulnerabilities found in PHP applications and their mitigation.
SQL Injection
Top on the PHP scripting hit list is SQL Injection attacks, where a single query can potentially compromise the entire application. In this case, an attacker will try to alter or by-pass data you are processing via SQL queries.
By inputting vulnerable data to the SQL interpreter, unintended commands may be executed. This may include inserting, updating, or even deleting data from the database.
Suppose you have a PHP login form containing text fields for the username and password, the backend code will be as follows:

This code snippet contains a loophole in that if you enter ‘ or ‘y’=’y ‘or’ then the variable $password will have the value ‘ or ‘y’=’y ‘or’ The resulting query is updated as follows.

In the updated statement, y=y is always true. This means the statement is executed without the actual matching of passwords.
This is just one of the simplest forms of SQL injection. There are cases where an attacker can create a query that adds data to the legitimate program such that it becomes part of the program body. Depending on the data passed, you might have a user table deleted or modified.
Before moving forward to the mitigation details, we need to understand what causes SQL injection attacks. Here are some things that facilitate these types of attacks.
- Incorrect type handling
- Incorrectly filtered space characters
- Mixing code and data.
- Passing unsanitized data to the database
- Using quotation marks to delimit strings
Solutions
Preventing SQL injection in PHP is quite an extensive topic. Here are two methods that can successfully solve the injection issue.
Using PHP Prepared Statements
A prepared statement allows users to execute SQL queries without storing the variables. It separates the query from the data such that hackers cannot use data submitted to alter how a query runs, thus preventing SQL injection attacks. Below is a good example demonstrating how prepared statements work.

This is the best way to write queries. Notice how the query is sent to the server before binding the expected data.
Using the PHP str_replace() Function
The PHP str_replace() function replaces some characters in a string with other characters to create secure functions. Here’s a practical example of this effective SQL injection prevention technique.
Create a function like:

In the above example, str_replace() supersedes all characters in the string and the resulting function will be:

Cross-Site Scripting
Cross-site scripting, also known as XSS, is another common vulnerability among PHP applications. It often occurs when programmers fail to validate their input or sanitize their output.
Basically, an attacker injects malicious code through a web form or sends an infected code to the target using an altered hyperlink. The injected code could be VBScript, HTML, Flash, CSS, JavaScript, or any other client-side code.
Attackers use cross-site scripting for stealing cookies, keylogging, or even taking control of the browser to obtain sensitive information.
Here is an example XSS script that targets the client’s cookies.

If an attacker injects this code through a web application’s vulnerable field, it will be executed in the client’s browser and cookies sent to the attacker.
Solutions
The rule of thumb in programming is that you should never trust any data coming from users or third party users. This is the first step of preventing cross-site scripting attacks at any stage of development.
As you write every single line of code, focus on the three main aspects of secure data processing i.e. input validation, output escaping, and data sanitization.
Input Validation
Input validation is the process of ensuring a web application runs with the correct data. It is an effective way of preventing XSS attacks in forms by disallowing certain characters in the user input. In this case, every piece of user data that does not match the defined type or predetermined format is rejected.
When validating a mobile phone number, for instance, you would discard strings that contain letters and special characters that are not used in phone number formatting.
Here is a good example that validates the phone number of a user based in Texas City, USA. Note how we allow special characters such as parenthesis and dashes as well as code prefixes specific for the intended location.

For an application that allows users to input their names, the text box should only accept letters, dashes, and spaces. This statement can be used to validate user input.

Data Sanitization
It is totally possible for some types of malicious input to pass the validation process, so you need to ensure the data is not harmful by sanitizing it. Data sanitization is a stronger defense that involves scrubbing off unwanted pieces of data and normalizing it to the desired form.
For example, if an application allows users to input comments as a plain text string, you should remove any HTML to ensure data received does not harm users of interfere with the database. This statement will sanitize all HTML markup from the comments:

In some cases, data validation and sanitization goes hand in hand as shown below

Keep a keen eye on security vulnerabilities
One ideal way of minimizing common attacks is by following PHP coding best security practices such as input validation and proper error handling. However, vulnerabilities are inevitable in today’s world, where new forms of attack are constantly coming up.
The best security approach is to continuously check whether your applications are vulnerable to attacks using automated solutions. This is relatively easy as the open-source community does a great job by reporting security vulnerabilities and providing fixes.
WhiteSource’s Vulnerabilities lab, for instance, keeps track of all CVE’s identified over the years. Its massive yet searchable database contains over 175,000 vulnerabilities published alongside their remediation suggestions.

Information regarding any CVE entry such as threat description, severity score, weakness type as well as CVSS v2 and v3.x scores can be found on the vulnerabilities dashboard. The WhiteSource vulnerabilities lab also offers links to great resources that keep you informed about respective CVEs, thus giving you complete control and transparency regarding your applications and potential vulnerabilities.