The PHP addslashes() function is used to add backslashes before certain characters in a string. This is particularly useful when preparing a string for storage in databases or handling special characters like quotes in SQL queries.
Syntax
string addslashes ( string $string )
$string: The input string where special characters will be escaped by backslashes. Return Value: A string with backslashes added before the following characters: single quote ('), double quote ("), backslash (\), and NULL.
Basic Example of addslashes()
In the following example, we apply the addslashes() function to escape quotes in a string.
$str = "John's book";
echo addslashes($str); // Output will add backslashes before the single quote
Output:
John\'s book
Example with Multiple Special Characters
This example demonstrates how addslashes() adds backslashes before multiple special characters in a string.
$str = 'He said, "It\'s a test!"';
echo addslashes($str); // Backslashes added before single and double quotes
Output:
He said, \"It\'s a test!\"
Example with Backslashes
The addslashes() function doesn't escape backslashes that are already part of the string
$str = "C:\\Program Files\\";
echo addslashes($str); // No additional backslashes
Output:
C:\\Program Files\\
Escaping NULL Characters with addslashes()
When using the addslashes() function, the NULL character (`\0`) is also escaped by adding a backslash. However, because NULL represents the end of a string in many contexts, it may not appear in regular output. To demonstrate this, we can use var_dump() to visualize the escaped NULL character.
$str = "A NULL character \0 is here.";
echo "Output with echo: " . $str . "<BR>"; // The output will end after the NULL character
// To display the full string, including the escaped NULL, we use var_dump
var_dump(addslashes($str));
Output:
Output with echo: A NULL character
string(28) "A NULL character \0 is here."
As you can see, the addslashes() function adds a backslash before the NULL character, but the regular `echo` only prints up to the NULL character. Using var_dump(), we can see the full string including the escaped NULL.
Using addslashes() in SQL Queries
The addslashes() function is commonly used to escape special characters in SQL queries to prevent SQL injection.
$name = "O'Reilly";
$sql = "SELECT * FROM users WHERE name = '" . addslashes($name) . "'";
echo $sql;
Output:
SELECT * FROM users WHERE name = 'O\'Reilly'
Conclusion
The PHP addslashes() function is essential when handling strings that contain special characters, particularly when preparing data for SQL queries. It ensures that characters like quotes and backslashes are properly escaped to avoid syntax errors or potential security vulnerabilities such as SQL injection.