PHP addslashes() Function
PHP’s addslashes() returns a new string with single quotes, double quotes, backslashes, and NUL bytes escaped. Use it when a format explicitly requires those backslash escapes. To pass a value to a database query, bind the original string to a prepared statement.
Which characters change?
addslashes(string $string): string
The function takes one string and leaves the input variable untouched. It prefixes each single or double quote with a backslash and doubles every existing backslash. It represents a NUL byte, whose numeric value is zero, as a backslash followed by the digit zero. The digit 0 on its own and the forward slash / are unchanged.
Check the output and restore the original
In a terminal with PHP installed, save the example as addslashes-demo.php and run php addslashes-demo.php. The array contains one string for each character that changes and a comparison string whose characters remain unchanged.
<?php
$examples = ["'PHP", '"PHP', '\\PHP', "A\0B", '0/PHP'];
foreach ($examples as $original) {
echo addslashes($original), PHP_EOL;
}
echo PHP_EOL;
$original = implode(' | ', $examples);
$escaped = addslashes($original);
var_dump(stripslashes($escaped) === $original);
\'PHP
\"PHP
\\PHP
A\0B
0/PHP
bool(true)
The first three lines show a new backslash before each quote or backslash. The \0 on the fourth line makes the otherwise invisible NUL byte visible. The final true means stripslashes() restored the escaped example byte for byte. Calling addslashes() again on an escaped value adds more backslashes.
Choose an encoder for the destination
addslashes() cannot protect a SQL query against injection. With PHP Data Objects (PDO), use a prepared statement with a parameter for the value and supply the original string to execute(). For text in HTML, use htmlspecialchars() to convert the relevant characters to HTML entities. For JSON data, encode the value with json_encode().



