A Comprehensive Guide to Hardening PHP Applications: Best Practices and Addressing Common Vulnerabilities

Securing PHP applications is critical to safeguarding both your application and its users from potential threats. In this guide, we’ll delve into common vulnerabilities and share best practices to strengthen your PHP applications against attacks.

Before diving into the details, check out this resource for practical examples on optimizing your PHP code for faster and more efficient performance.

A. Understanding Common Vulnerabilities in PHP Applications

Below are some of the most common security vulnerabilities in PHP applications and how to mitigate them effectively.

1- SQL Injection (SQLi)

  • SQL injection occurs when untrusted user input is merged directly into SQL queries without proper sanitization.
<?php
$user_input = $_POST['username'];
$query = "SELECT * FROM users WHERE username = '$user_input'";
?>
  • A safer approach would be to use a filtered usage like the one below rather than a usage similar to the one above.
<?php
$unsafeInput = $_POST['input'];
$safeInput = mysqli_real_escape_string($conn, $unsafeInput);
$query = "SELECT * FROM table WHERE column = '$safeInput'";
?>
  • A measure like the one above may not always work for you.There are already functions in php that are created to make ready-made and secure queries in order to make more secure queries for sql queries.You can examine it in the example below.
<?php
$username = $_POST['username'];
$password = $_POST['password'];

$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();

$user = $stmt->fetch();
?>
  • Assign database users the least privilege required. Avoid using super user accounts in your application.

2- Cross-Site Scripting (XSS)

  • XSS vulnerabilities allow attackers to inject malicious scripts into web pages viewed by other users, the type of xss we are talking about is reflected or stored xss.
<?php
echo "Hello, " . $_GET['name'];
?>
  • As above, if we reflect the input received from the user without any filtering (In the example, it works with the get parameter), the attacker can run the javascript code he wants over the url.Although the examples I have given here are very simple examples, in general, the source of the problem is caused by the lack of filtering. The safe way to use it is as follows.
<?php
$input = $_GET['name'];
$safe_input = htmlspecialchars($input);

echo "Hello, " . $safe_input;
?>

3- Code Injection

  • Code injection vulnerabilities allow attackers to execute arbitrary code on the server. This often happens when user inputs are executed directly without validation.
  • Usage like the one below could allow malicious actors to execute code on your server. As a precaution, avoid running on user-supplied input and look for alternatives even when necessary.
<?php
$filename = $_GET['file'];
include($filename);
?>

4- Directory Traversal

  • Protect against directory traversal attacks by ensuring that user-supplied file paths do not go outside the intended directory.
<?php
$file = '/path/to/user/supplied/file.txt';
$basePath = '/path/to/allowed/directory/';

if (strpos(realpath($file), $basePath) === 0) {
    // The file is within the allowed directory
    // Proceed with operations
} else {
    // Handle invalid file path
}
?>

B. Additional Security Measures for PHP Applications

Beyond addressing common vulnerabilities, implementing additional security measures is essential to further protect your PHP applications from evolving threats. These practices enhance overall security by addressing areas often overlooked.

1- Use Anti-CSRF Tokens

  • CSRF attacks aim to abuse the trustworthiness of a user session to perform a targeted operation without the user’s knowledge.For example, by exploiting an open session in a user’s browser, a malicious site could perform a transaction on behalf of that user (e.g. transferring money, account changes, etc.).
  • Anti-CSRF tokens provide an additional layer of security to prevent such attacks.A unique token is generated for each user session and sent to the client side (e.g. the browser).
<?php
// Generate and store CSRF token
$csrfToken = bin2hex(random_bytes(32)); 
$_SESSION['csrf_token'] = $csrfToken;

// Include the token in forms
<input type="hidden" name="csrf_token" value="<?= $csrfToken; ?>">
?>

2- Set Security Headers

  • Security headers are HTTP headers that a web server sends in its response to a browser. They communicate certain rules to the browser regarding content and behavior and prevent malicious activity.
<?php
// Enable content security policy (CSP)
header("Content-Security-Policy: default-src 'self'");

// Prevent MIME-type sniffing
header("X-Content-Type-Options: nosniff");
?>

To identify missing security headers on your website, visit the following page:
Security Headers Check

3- Set Secure and HttpOnly Flags for Cookies

  • The Secure flag ensures that cookies are transmitted exclusively over encrypted HTTPS connections. This prevents attackers from intercepting sensitive data during unencrypted HTTP transmissions, adding an essential layer of protection to your application’s security.
  • Httponly,  It ensures that the cookie is only accessible on the server side.Client-side code such as JavaScript cannot access the cookie. This provides protection against XSS (Cross-Site Scripting) attacks.
<?php
// Set a session cookie
setcookie(
    "session_cookie",  // Cookie name
    $value,            // Cookie value
    time() + 3600,     // Expiration time (1 hour)
    "/",               // Path
    "example.com",     // Domain
    true,              // Secure flag (HTTPS only)
    true               // HttpOnly flag (accessible only via HTTP(S))
);
?>

4- Avoid Dangerous Functions

  • Certain PHP functions can pose significant security risks to your website if not used carefully. You can find a list of these potentially dangerous functions at the link below. Exercise extreme caution when utilizing any of the functions mentioned to ensure your application remains secure.
    View the list of risky PHP functions

5- Manage Third-Party Dependencies Safely

  • When using third-party packages or libraries in PHP applications, it is very important to keep security considerations in mind. Keep third-party dependencies updated to patch known security vulnerabilities. Use Composer or package manager commands for updates.
  • To scan your project’s dependencies for known vulnerabilities, you can use powerful tools like OWASP Dependency-Check or S4E These tools help ensure your application remains secure by identifying and addressing potential risks in third-party libraries.

What is PHP ?

PHP (Hypertext Preprocessor) is an open-source, general-purpose programming language for server-side web development. It is widely used to create dynamic web pages and applications. PHP can be embedded in HTML and runs on the server, sending dynamic content to the browser.

Php Features:

  • Server-Side Language: PHP is invisible to the user because it runs on the server. The server executes PHP commands and sends the results to the browser in HTML format.
  • Database Integration: PHP can easily integrate with popular databases, especially MySQL and PostgreSQL. In this way, it is often used to develop dynamic web applications.
  • Easy Learning and Operation: PHP is a fairly easy language to learn and use, which is why it is popular for beginners. Its simple syntax and flexibility make it possible to quickly build advanced web applications.
  • Platform Independence: PHP can run on most platforms (Windows, Linux, macOS), which makes the development and deployment process more flexible.
  • Various Frameworks: Popular frameworks such as Laravel, Symfony, CodeIgniter are available to save developers time when working with PHP. These frameworks speed up common web development processes and offer an organized code structure.

Vulnerabilities in PHP

  • In addition to the table below, numerous vulnerabilities exist, including the CVE-2024-4577 vulnerability identified in 2024. Furthermore, while the current version is 8.4.0, using any version below 8.3.8 poses a significant security risk. It’s crucial to keep your software up to date to safeguard against these threats.
A heatmap visualizing PHP vulnerabilities categorized by type from 2014 to 2024. The chart highlights key categories such as Overflow, Memory Corruption, SQL Injection, XSS, and Input Validation. The data shows a significant spike in Overflow and Memory Corruption vulnerabilities in 2016, while other categories like Input Validation remain relatively steady. This breakdown provides insights into the historical trends of PHP security risks.
Table displaying PHP version-dependent vulnerabilities, highlighting various versions from 8.3.0 to 8.3.8 with associated vulnerability counts. Critical for understanding cybersecurity risks and maintaining updated software versions.