Worldscope

addslashes()

Palavras-chave:

Publicado em: 04/08/2025

Understanding and Using addslashes() in PHP

The `addslashes()` function in PHP is used to add backslashes before characters that need to be escaped in a string, particularly when preparing data for storage in a database. This article explains how `addslashes()` works, provides code examples, and discusses its implications for security.

Fundamental Concepts / Prerequisites

To understand `addslashes()`, you need a basic understanding of the following:

  • **String Escaping:** The process of modifying a string to ensure that special characters are interpreted literally rather than as control characters. This is critical for preventing SQL injection and other vulnerabilities.
  • **PHP Strings:** Knowledge of how strings are represented and manipulated in PHP.
  • **Database Interactions (Optional):** Familiarity with how data is inserted into a database using PHP. While not strictly necessary, understanding this context will help clarify the purpose of `addslashes()`.

Core Implementation/Solution

The `addslashes()` function takes a string as input and returns a new string with backslashes added before specific characters. These characters are single quote ('), double quote ("), backslash (\), and NUL (the null byte).


<?php

/**
 * Example demonstrating the use of addslashes() in PHP.
 *
 * @param string $string The string to be escaped.
 * @return string The escaped string.
 */
function demonstrateAddSlashes(string $string): string {
  $escapedString = addslashes($string);
  return $escapedString;
}

// Example Usage:
$originalString = "This is a string with 'single quotes' and \"double quotes\" and a \\ backslash.";
$escapedString = demonstrateAddSlashes($originalString);

echo "Original String: " . $originalString . "<br>";
echo "Escaped String: " . $escapedString . "<br>";

$anotherString = "String with a null byte: \0";
$escapedAnotherString = demonstrateAddSlashes($anotherString);
echo "Original String: String with a null byte: " . bin2hex($anotherString) . "<br>"; // use bin2hex() to display null byte, raw output not allowed
echo "Escaped String: String with a null byte: " . bin2hex($escapedAnotherString) . "<br>"; // use bin2hex() to display null byte, raw output not allowed

?>

Code Explanation

The `demonstrateAddSlashes()` function takes a string as input. Inside the function, `addslashes($string)` is called. This function examines the input string and inserts a backslash (`\`) before each occurrence of a single quote (`'`), a double quote (`"`), a backslash (`\`), or a NUL byte (`\0`). The modified (escaped) string is then returned by the function.

The example shows the original and escaped strings printed using `echo`, allowing you to see the effect of `addslashes()`.

The bin2hex() function is employed to correctly display null bytes in the output, as echoing the raw null byte can create issues with the page rendering.

Complexity Analysis

The `addslashes()` function iterates through the input string once to identify characters that need to be escaped. Therefore:

  • **Time Complexity:** O(n), where n is the length of the input string. The function needs to examine each character in the string.
  • **Space Complexity:** O(n) in the worst-case scenario, where many characters need to be escaped, because a new string is created to store the escaped version. In the best-case scenario (no characters need escaping), the space complexity is closer to O(1) because only minimal overhead is required.

Alternative Approaches

While `addslashes()` might seem suitable for database escaping, it is generally **not recommended** for modern PHP development, especially when interacting with databases. Prepared statements and parameterized queries offer a significantly more secure and robust alternative.

Prepared Statements (using PDO or MySQLi): These methods allow you to separate the SQL code from the data. The database handles the escaping automatically and securely, preventing SQL injection vulnerabilities.


<?php
// Example using PDO (PHP Data Objects)
try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $username = $_POST['username']; // Example: user input

    // Prepare the SQL statement
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

    // Bind the parameter
    $stmt->bindParam(':username', $username, PDO::PARAM_STR);

    // Execute the query
    $stmt->execute();

    // Process the results...
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($results as $row) {
        echo "User ID: " . $row['id'] . "<br>";
    }

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>

Prepared statements eliminate the need for manual escaping, improving security and code maintainability. They are the preferred way to handle user input when interacting with databases.

Conclusion

`addslashes()` is a PHP function used to escape certain characters in a string. While it may have had its uses in the past, it's generally considered less secure than using prepared statements or other database-specific escaping mechanisms. Modern PHP development should focus on using prepared statements (PDO or MySQLi) to protect against SQL injection and other security vulnerabilities.