How to prevent code injection attacks in PHP?

How to prevent code injection attacks in PHP?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Preventing Code Injection in PHP: Beyond the Confusion of Escaping Functions

The debate over escaping functions in PHP has persisted for a long time, often leaving developers confused about which tool to use when. You will frequently encounter suggestions to mix and match htmlspecialchars(), htmlentities(), strip_tags(), and various escape functions like mysql_real_escape_string. The core misunderstanding usually stems from conflating two distinct security problems: injection attacks within the database layer and Cross-Site Scripting (XSS) vulnerabilities in the output layer.

To secure your application, you must treat these layers separately. Each function serves a specific purpose based on where the data is being processed.

The Database Layer: Parameterized Queries vs. Escaping

Your source material suggests using mysql_real_escape_string() to prevent MySQL injection attacks when inserting strings into the database. While this function was effective in legacy code using the deprecated mysql_* extension, it is no longer recommended for new development due to security flaws and lack of support in modern PHP versions.

The fundamental principle for preventing SQL injection is never to manually escape individual variables before binding them to a query. Instead, you should use parameterized queries (prepared statements). This approach ensures that the database engine treats user input strictly as data, never as executable code, regardless of the characters contained within it.

In modern PHP using PDO or MySQLi, the correct implementation looks like this:

$pdo = new PDO($dsn, $username, $password);

$stmt = $pdo->prepare("INSERT INTO users (username) VALUES (:username)");
$stmt->execute(['username' => $_POST['username']]);

If you are forced to use the deprecated mysql_* functions or raw strings for some legacy reason, then mysql_real_escape_string() is indeed required before concatenating variables into a query. However, it does not protect against XSS; it only neutralizes special characters like quotes and backslashes specifically for SQL parsing.

The Output Layer: Preventing XSS

Preventing SQL injection is irrelevant to Cross-Site Scripting (XSS). An XSS attack occurs when malicious JavaScript code is executed in a user's browser, typically because the application rendered untrusted data directly into an HTML element without neutralizing it.

To prevent this, you must encode special characters (<, >, &, ", ') before outputting them to the browser. The standard and correct function for this in modern PHP is htmlspecialchars().

Your source material mentions htmlentities() as well. The primary difference lies in character encoding:

  • htmlspecialchars() converts only the five special characters that have meaning in HTML/XML. It also handles the UTF-8 encoding correctly by default when using the ENT_QUOTES flag, which is crucial for preventing both HTML and JavaScript injection.
  • htmlentities() converts all non-ASCII characters to their corresponding hexadecimal entities (e.g., converting an 'é' to &#233;). This can sometimes lead to double-encoding issues or unnecessary bloat if the content is already UTF-8.

For almost all cases involving outputting data into a webpage, htmlspecialchars() with ENT_QUOTES and UTF-8 encoding is the superior choice:

echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

Clarifying the Other Functions

Based on your questions regarding when to use specific functions, here is the breakdown of their intended uses and limitations:

  • strip_tags(): This function removes HTML tags from a string. It should generally be avoided for security purposes because it does not sanitize content; it merely strips known tags while leaving attributes intact (e.g., <img src="..." onload="alert('xss')">). If you need to allow some HTML, use DOMDocument or specific sanitization libraries like HTML Purifier rather than blind stripping. Use this only if you strictly require plain text output and want to ensure no markup exists, but always prefer encoding over stripping for security.
  • addslashes(): This function adds backslashes before single quotes, double quotes, and backslashes. It is considered unsafe because it does not handle context correctly (e.g., inside a string literal vs. an SQL query) and ignores character set nuances. It has largely been superseded by parameterized queries for database contexts and htmlspecialchars() for output contexts.
  • mysql_real_escape_string(): As noted, this is strictly for legacy MySQL contexts to escape data before it enters a query string. It should not be used for HTML escaping because the set of characters escaped differs from what is needed to prevent XSS.

Summary of Best Practices

To conclude, the workflow for secure PHP development is distinct:

  1. Input/Database: Always use prepared statements. Do not manually escape data with mysql_real_escape_string or addslashes.
  2. Output/Browser: Always encode output using htmlspecialchars() with ENT_QUOTES and 'UTF-8' before echoing or printing to HTML elements.

By separating the concerns of database integrity from browser rendering, you eliminate the confusion surrounding these functions and build a more robust application. For those looking to implement these patterns quickly within a framework ecosystem, Laravel provides robust bindings for PDO that handle prepared statements automatically, ensuring SQL injection is mitigated by default while offering Blade templating engines that automatically escape variables outputted with {{ }} syntax.

Our network