7 Common PHP Security Vulnerabilities and How to Fix Them

As per the statistics, PHP is still one of the most poular server-side programming languages, which is the one using a server located on the side, supporting up to 85% of all the websites. This significantly high number is one of its overwhelming advantages. In addition to that, there are ongoing issues that arise in security that keep on making headlines as well. Within this context, it is important to comprehend the most common PHP security defects as well as the methods for their solution for a developer, so their products do not have any vulnerabilities.

1. SQL Injection (SQLi)

What is it?
SQL Injection occurs when an attacker manipulates SQL queries by injecting malicious SQL code through user inputs. This can lead to unauthorized access to databases, data theft, or even complete database deletion.

Real-World Example:
Imagine a login form where the username and password fields are directly used in an SQL query:

$query = "SELECT * FROM users WHERE username = '$_POST[username]' AND password = '$_POST[password]'";

An attacker could input ' OR '1'='1 as the username, bypassing authentication.

How to Fix It:

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->execute(['username' => $_POST['username'], 'password' => $_POST['password']]);
  • Validate and sanitize all user inputs.
  • Avoid using raw SQL queries with user inputs.

2. Cross-Site Scripting (XSS)

What is it?
XSS attacks occur when an attacker injects malicious JavaScript code into a web page, which is then executed in the browser of another user. This can lead to session hijacking, defacement, or data theft.

Real-World Example:
A comment section that doesn’t sanitize user input:

echo "<div>" . $_POST['comment'] . "</div>";

An attacker could submit a comment like <script>alert('XSS Attack!');</script>, which would execute in other users’ browsers.

How to Fix It:

  • Use htmlspecialchars() or htmlentities() to escape output:
echo "<div>" . htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8') . "</div>";
  • Implement Content Security Policy (CSP) headers to restrict the execution of inline scripts.
  • Validate and sanitize all user inputs.

3. Cross-Site Request Forgery (CSRF)

What is it?
CSRF attacks trick users into performing actions they didn’t intend to, such as changing account settings or making purchases, by exploiting their authenticated session.

Real-World Example:
A form that doesn’t use CSRF tokens:

<form action="/change_password" method="POST">
    <input type="password" name="new_password">
    <input type="submit" value="Change Password">
</form>

An attacker could create a fake form on another site to submit malicious requests.

How to Fix It:

  • Use CSRF tokens to validate requests:
session_start();
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;

// In the form:
<input type="hidden" name="csrf_token" value="<?php echo $token; ?>">

// On form submission:
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    die("CSRF token validation failed.");
}
  • Implement SameSite cookies to restrict cross-origin requests.

4. File Inclusion Vulnerabilities

What is it?
File inclusion vulnerabilities occur when an attacker can include malicious files (local or remote) through user inputs, leading to code execution or sensitive data exposure.

Real-World Example:
A script that includes files based on user input:

$page = $_GET['page'];
include($page . '.php');

An attacker could manipulate the page parameter to include a malicious file.

How to Fix It:

  • Avoid using user inputs in file inclusion functions.
  • Use whitelists for allowed files:
$allowed_pages = ['home', 'about', 'contact'];
if (in_array($_GET['page'], $allowed_pages)) {
    include($_GET['page'] . '.php');
} else {
    die("Invalid page request.");
}
  • Disable allow_url_include in your php.ini file.

5. Session Hijacking

What is it?
Session hijacking occurs when an attacker steals a user’s session ID, allowing them to impersonate the user and gain unauthorized access.

Real-World Example:
If session IDs are transmitted over unencrypted connections, attackers can intercept them using tools like packet sniffers.

How to Fix It:

  • Use HTTPS to encrypt all communications.
  • Regenerate session IDs after login:
session_regenerate_id(true);
  • Set secure session cookie attributes:
ini_set('session.cookie_secure', 1);
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_samesite', 'Strict');

6. Insecure File Uploads

What is it?
Insecure file uploads allow attackers to upload malicious files (e.g., PHP shells) to the server, which can lead to remote code execution.

Real-World Example:
A file upload feature that doesn’t validate file types:

move_uploaded_file($_FILES['file']['tmp_name'], '/uploads/' . $_FILES['file']['name']);

An attacker could upload a .php file and execute it.

How to Fix It:

  • Validate file types and extensions:
$allowed_types = ['image/jpeg', 'image/png'];
if (in_array($_FILES['file']['type'], $allowed_types)) {
    move_uploaded_file($_FILES['file']['tmp_name'], '/uploads/' . basename($_FILES['file']['name']));
} else {
    die("Invalid file type.");
}
  • Store uploaded files outside the web root.
  • Use random file names to prevent overwriting.

7. Insecure Configuration


What is it?


Insecure PHP configurations, such as displaying errors or enabling dangerous functions, can expose sensitive information or create attack vectors.

Real-World Example:
A production server with display_errors enabled, revealing database credentials in error messages.

How to Fix It:

Update your php.ini file with secure settings:

display_errors = Off
log_errors = On
allow_url_fopen = Off
disable_functions = exec,passthru,shell_exec,system
  • Regularly update PHP to the latest stable version.
  • Use tools like PHPStan or Psalm to analyze your code for vulnerabilities.

Conclusion

PHP’s flexibility and ease of use make it a favorite among developers, but its power comes with responsibility. By understanding and addressing these common security vulnerabilities, you can build robust, secure applications that protect both your users and your reputation. Remember, security is not a one-time task but an ongoing process. Stay vigilant, keep learning, and always prioritize security in your development workflow.