facebook 9 PHP Vulnerability Examples & How To Fix Them

Nine Severe PHP Vulnerabilities & How to Fix Them

Summary: With a 45.43% market share, PHP is a pragmatic language widely used for web application development. It is a tool used for dynamic and effective web applications, and like all programming languages, it remains vulnerable and subject to security flaws. This article will guide you on how to secure your website against common PHP vulnerabilities like SQL injection attacks, cross-site scripting, session fixation, etc.

How often have you heard the statement “PHP is dead”?

To say the least, PHP:

  • Has a presence of more than 25 years.
  • Is the power behind 80% of websites.
  • Forms a base for the computing infrastructure of many corporate giants.
  • Boasts of an impressive list of ‘Stars’ like WordPress, Facebook, Slack, Etsy, and Mailchimp.

With its dynamic nature, immense credibility, and consistent popularity in the tech & retail sphere, PHP invites debate & discussion very frequently – and issues related to security top the list! A massive user base and an active community make PHP vulnerable to continuous attacks & security threats.

Research shows that PHP has the highest incidence of security flaws, making it an ideal prey for cybercriminals. The language has application level vulnerabilities which make it prone to malicious attacks.

15-Point web app development checklist

We respect your privacy. Your information is safe.

Why is PHP not secure?

While a language cannot possibly be wholly or inherently insecure, PHP did start with some fundamental security loopholes. PHP wasn’t built using the Secure By Design guiding principle – incorporating security features in the software from the ground up so that end users/programmers do not struggle through various stages to see how they can secure their usage.

All applications & libraries written in PHP have basic security vulnerabilities. Native functionality is missing, and PHP undermines the safeguarding needed against potential attacks.

There are enough PHP functions to carry out system tasks like file manipulation, database access, and network operations. Attackers can exploit these functions to compromise and control servers through web shell applications.

While the above does imply that the onus of security falls on the end-users, it doesn’t mean we can challenge or question the status of PHP as a language. There are ways to identify and address PHP vulnerabilities before they compromise your servers, damage your reputation, and make you vulnerable to litigation by exposing user data.

Top 9 PHP vulnerabilities & how to fix them

PHP code Vulnerabilities are a result of gaps left while writing the original code. You could say that ‘vulnerabilities’ occur because of ‘unsanitized’ user input. Web applications accept inputs from the user, and if the information contains malicious code, it gets passed on to the application and creates vulnerabilities. Running scripts on unsanitized inputs can create vulnerabilities.

Listed below are some of the key PHP vulnerabilities:

1. Cross-site Scripting (XSS) Attack

A cross-site scripting attack happens when an attacker injects a malicious HTML or JavaScript code into your website to steal passwords and user cookies or gain administrator-level access.

Let’s understand how cross-site scripting works with the help of an example. Suppose you wrote the following code to display a welcome message on your website:

PHP Code Script for Welcome Message

The purpose of this code is to print a welcome message to the logged-in user. The username is retrieved using the GET variable that stores values of query string parameters in the form of pairs passed through the HTTP GET method.

The server will return the following output:

Welcome user1 (user1 is the fetched user name. Let’s say John, Steve, or Mark.)

A malicious user can modify this code to exploit XSS vulnerability if your website is not following security measures. As a result, they can take control of the browser, use keylogging to steal passwords, or even steal cookies. A single XSS attack can cost you millions in lost business and reputation.

Three types of cross-site scripting attacks exist, i.e., Reflected, Persistent, and DOM-based XSS.

  • Reflected XSS Attacks:This is the most common XSS vulnerability. It occurs when the untrusted user data is sent to the web application and echoed back as untrusted content. This vulnerability occurs on the server side.
  • Persistent XSS: This XSS attack stores within the web application in the database rather than reflecting the malicious user’s input in the response. Once it occurs, it is echoed back to all web application users. These types of flaws occur in server-side code.
  • DOM-based XSS: Attackers execute this XSS attack by modifying the DOM environment in the victim’s browser. It is possible if the web application writes data to the document object model (DOM) without proper sanitization. The attack only exists in client-side code.

XSS Attacks

How do you protect your website against XSS Attacks?

  • Use a web application firewall (WAF) like Cloudflare. It blocks any potentially malicious code and ensures nothing is executed on your website without your permission.
  • Use an XSS-protection header to enable a cross-site-scripting filter on your browser. It would automatically sanitize your page whenever it detects a scripting attack.
  • Apply htmlspecialchars() and htmlentities() functions which convert special characters into HTML entities. This way, you escape the string from unknown sources such as the user input and prevent XSS attacks.
  • Use the strip_tags() function to remove content between HTML tags and ensure it doesn’t encode or filter non-paired closing angular braces.
  • The addslashes() function can also prevent XSS attacks by stopping attackers from terminating variable assignments and adding the executable code at the end.
  • Use the content security policy (CSP) header to whitelist a set of trusted sources and put restrictions on attackers’ actions.
  • Some third-party PHP libraries like htmLawed, PHP Anti-XSS, and HTML purifier can also prevent your website from attacks against XSS attacks.

2. Cross-site Request Forgery (CSRF) Attack

The CSRF attack tricks website owners into clicking on a malicious link that can invisibly override access, steal session information, or automatically send legitimate-looking commands to the server on your behalf.

Here’s an example of how the cross-site request forgery attack works:

Cross site request forgery attack

How do you prevent cross-site request forgery (CSRF) Attacks?

Your best course of action against CSRF attacks is to use authentication tokens. It’s difficult for hackers to perform authorized action when a new token is generated on each login. WordPress uses ‘nonce.’ It changes daily, making it challenging for malicious actors to hack into a website.

However, the challenge with ‘nonce’ is that some WordPress plugins don’t use it, which can unexpectedly introduce vulnerabilities to the website. You must be vigilant and ensure any plugins you use have the nonce system from WordPress.

3. SQL Injection

In the SQL injection PHP exploit, an attacker fools the server-side code by injecting an unsanitized SQL command into the database. As a result, the SQL query returns information the web application doesn’t intend to expose, such as database content, private details, passwords, etc. Sometimes, an SQL injection attack may even grant access to the entire website.

Any malicious user can access the back-end database of the web application with SQL injection. It would allow him to do privilege escalations at the application level. When a SQL server is running under the context of system admin (DBO, SA), a malicious user would be able to own the entire server.

Here’s an example of a code vulnerable to SQL-injection attack:

SQL Injection  Attack Vulnerable Code Example

The above code is vulnerable to SQL Injection since none of the POST variables – username and password – are filtered or sanitized. Code blindly accepts whatever the username and password contain, which is dangerous as it can compromise the application and, later, the entire server.

SQL Injection Attack

How to Prevent SQL-injection Attacks?

To prevent SQL injection attacks, be mindful of any input you accept from the user. Use parameterized queries and prepared statements in your code instead of plain-text questions with no input sanitation.

4. File Inclusion Attacks

File Inclusion Attack
File inclusion attacks misuse the ability of websites to accept uploaded content like images and documents. Two types of file inclusion attacks exist:

  • Remote File Inclusion Attack: Hackers fool your PHP code into accepting a URL containing malicious code as valid input on another site. This way, they gain access to your website and exploit it. For example, if you have a website www.myplace.com and a hacker tricks your PHP code into including a library www.goodreviews.com/script.php containing malicious code, the malicious code will load into your website and allow the hacker to breach it.
  • Local File Inclusion Attack: Attackers trick your PHP code into passing a local file and displaying its contents on the screen. They use it to access the wp-config.php file of the WordPress website.

How to Prevent File Inclusion attacks?

To prevent these attacks, look for the insecure implementation of the include, include_once, fopen, file_get_contents, require, and require_once PHP functions. Most of the remote and local file inclusion attacks include them.

Also, you can check the settings on these flags from php.ini:

  • allow_url_fopen: It indicates whether the external files can be included in your website or not. Turn off this setting if the default is set to on.
  • Allow_url_include: This flag indicates whether the include(), require(), include_once(), and require_once() functions can reference remote files. The default setting is off.

5. Session Hijacking

In session hijacking, an attacker steals the session ID of a user. Once the attack has the session ID, it can access everything that happened during that session. For example, if you used that session to log in to a website or authenticate a user, attackers can use that session to sign in and exploit your website.

Session hijacking is dangerous, especially when you’re an admin, because a stolen session, in that case, can do significant damage.
Session Hijacking

How to Prevent Session Hijacking?

You can start with changing session ID using session_regenrate_id() and preventing JavaScript from accessing session ID data using the session.cookie.httponly setting in php.ini and session_set_cookie_parms() function. Also, ensure session ID data is not stored in a publicly accessible folder because you’re at risk if that happens.

6. Authentication Bypass

Authentication bypass is the result of a developer error. It occurs when an app doesn’t validate a user’s credentials correctly and unknowingly gives them elevated access. For example, many beginner developers use the is_admin() function to determine if the user has administrator-level access. What they don’t understand is that the actual purpose of the function is to confirm whether someone is viewing an admin page. This way, they grant access to the wrong user who may misuse it.

How to Protect Your Website against Authentication Bypass?

Preventing authentication bypass PHP vulnerabilityrequires a code review by experienced developers. It ensures no logic mistakes happen in authentication and tokenization processes. Static application security testing tools can detect such flaws. You must know the user well before granting access.

7. Command Injection

A command injection attack works similarly to SQL injection. The only difference is that the command injection attack targets the system, and attackers perform it using the server’s operating system to run arbitrary commands.
Command injection attack

How to Prevent the Command Injection Attack?

Here are three things you need for a successful command injection PHP exploit:

  • The application uses a system call (passthru, system, or anything similar).
  • The command passed as an argument to the function is created using some external input.
  • The input is not validated or sanitized.

You only need to remove the above conditions to prevent a command injection attack. The best action is to avoid system calls as much as possible. Instead, you can use PHP’s built-in functions to interact with the operating system. For example, to know which files are present in the directory, you can use opendir and readdir. Similarly, to delete a file, you can use unlink instead of system(“rm $file”).

8. PHP Object Injection

With the PHP object injection attack, an attacker calls the unserialize() function with unsanitized user inputs to inject PHP objects into memory. A successful PHP object injection attack can result in further attacks like SQL Injection, Path Traversal, or even the complete web application shutdown.

How to Prevent PHP Object Injection Attack?

To prevent PHP object injection attacks, verify and sanitize each input your web application receives. It would ensure no PHP objects are submitted and your application is safe.

9. Remote Code Execution

The remote code execution PHP vulnerability allows attackers to upload malicious code to your website and remotely execute it. It happens when a bug in the PHP application accepts user inputs and misinterprets them as PHP code. It allows an attacker to create a new file that grants them complete access to your website.

Remote code execution

Remote code execution is a serious concern because it’s easy to exploit and grants attackers complete control over your website.

How to Prevent Remote Code Execution Attacks?

  • Keep your operating system and third-party software.
  • Always sanitize your inputs and ensure you don’t process them unless you’re sure they’re not malicious.
  • Have strong authentication and access protocols in place. It would ensure attackers don’t have access to the core system even if they get past existing security protocols.
  • Use web application firewalls to keep attackers at bay.

Validating and sanitizing data

PHP security entails securing your site against unauthorized access. You can start doing this in PHP by validating and sanitizing your site’s data.

Validating is the initial step and involves verifying the data entering the script. You need to check if it is the kind of data you need/want, the format, and the length of the data. Unless you do this, you are leaving your site vulnerable. Check the kind of data that comes in and the length of the variables. You also need to ensure that the format is correct so the information can be used correctly.

Where validating involves determining if the data is in the proper form, sanitization refers to removing any illegal characters in the data. PHP filters help in performing sanitizing and validating external input.

PHP filter extension and advanced filter perform the validation and sanitizing of external inputs. These external inputs could be cookies, web service data, server variables, and database query results. They could also be user inputs from forms. The filter function filter_var () validates and sanitizes data and filters a variable with a specified filter.

Look at the example below. Here the function is used to sanitize and remove illegal characters from the email variable:
Sanitizing Inputs PHP Code

How do you protect your PHP web application from cyberattacks?

Given the extent of PHP usage in web applications, security cannot be an option – it is a necessity. You could take the following steps to protect your application from PHP vulnerabilities:

1. Use Strong Passwords

Most PHP exploits happen because of weak or easily breakable credentials. So, keep your passwords secure and robust. Here’s how you can do that:

  • Include alphanumeric characters with both lower and upper case characters.
  • Use phrases as it takes a considerable amount of time to crack them.
  • Your passwords should be at least 7-16 characters long. The longer they are, the harder they’re to crack.

Also, change your passwords regularly to minimize hackers’ chances.

2. Use Multi-factor Authentication

Multi-factor authentication adds an extra layer of security and ensures attackers cannot cause any damage even if they have the credentials. An example is a two-factor authentication in WordPress, where users receive a login code on their registered email after entering their credentials. Only after adding the login code are they granted access to their WordPress account.

3. Use Data Filtering

Data filtering protects your website from malicious code snippets and SQL injection attacks. There are multiple ways to enable data filters. You can dedicate a single module to security and place it at the beginning of all publicly accessible scripts, including numerous security checkpoints or having several characters and string combinations.

4. Use a Web Application Firewall

A web application firewall offers complete protection by keeping malicious data from reaching your website. They can be your best bet against various cyberattacks. Mod_Security (ModSec) is one such firewall that adds an extra layer of security. It is available for Linux, Windows, Solaris, FreeBSD, and Mac OS X and integrates well with Apache HTTP server, IIS server, and Nginx server.

Mod_Security monitors and filters any incoming and outgoing data from the web server that does not satisfy its defined rules. It also blocks any special characters passed to GET or POST variables to rule out cross-site scripting, SQL injection, and other standard web attacks.

How Can Net Solutions Help You Build Secure PHP Websites/ Web Applications?

Tracking and fixing PHP vulnerabilities is fundamental to building secure websites and web applications. This calls for implementing code reviews, unit tests, and software security testing during the software development process. Partnering with trustworthy organizations could be the base for your organization to create robust products. Continuous delivery, ongoing innovation, increased opportunities for better ROI, and bottom-line growth is the contribution that collaborating with us entails.

At Net Solutions, we prioritize security and assist you in building stable & robust web applications & websites. We are an ISO 27001-certified organization competent in software design, testing, delivery, and maintenance. Our PCI-DSS compliant methods & processes enable us to build & deploy secure applications, including for regulated sectors such as FInance & Healthcare.

Agile methodology for software development brings an iterative development process, making it possible for us to build meaningful software. We can measure, test, and scale the solutions in markets, channels, and mediums that propel your business ahead.

Talk to us to avail our software development services. Check out how we helped Euro Car Parts (ECP), one of the leading car distributors in Europe, enhance its web presence and cater to a diverse audience with a secure website.

Euro Car Parts

Frequently Asked Questions

  • 01

    Is PHP safer than JavaScript?

    PHP is more secure because the code exclusively runs on the server and is not visible in the browser. It also remains a better tool for back-end development. Although not as fast as JavaScript, PHP wins for its server-side scripting. Real-time development of web applications involves a combination of both in many cases.

  • 02

    How do I scan PHP for malicious code?

    Scanners for malicious code in PHP are generally PHP web applications. You can test the remote and local PHP targets for all vulnerabilities. A complete analysis of the vulnerabilities and other details, like the current status, is updated in real-time during the testing process. PHP Antimalware Scanner is one example of a free tool to scan PHP targets.

  • 03

    Can hackers see my PHP code?

    Any attacker accessing your server (via FTP, your web hosting control panel, or exploiting a vulnerability) can see your PHP code. Hackers can attack the PHP web applications by attacking the application itself or the database where sensitive information like user information/passwords is saved.

  • 04

    Which is better, PDO or MySQLi?

    It depends on which database you’re using. PDO (Python Database Objects) supports over 12 database drivers, while MySQLi only supports MySQL. So, PDO makes more sense when you switch your project to other databases. MySQLi doesn’t support named parameters and PDO scores on that aspect.

Ready to build secure Web App?

Surabhi Shukla

About the Author

Surabhi Shukla is a dedicated PHP developer with a special forte as a Magento Certified Developer. Outside of her professional realm, Surabhi has a penchant for listening to jazz music and indulging in speed reading. However, she doesn't quite fancy podcasts that tend to drag on.

While she is still looking for her definitive claim to fame, she is known for being an "ever-dependable" team player. Problem-solving comes naturally to her. Her eye for detail and strategic thinking have lent perfection to many projects that she has worked on.

Pin It on Pinterest