PHP Reference ยท String Functions
PHP addslashes() and stripslashes() functions
Reference for PHP addslashes() and stripslashes(): which characters get a backslash, how to undo it, and why addslashes() is not safe for SQL queries.
addslashes() puts a backslash in front of four characters: the single quote, the double quote, the backslash itself and the NUL byte. stripslashes() does the opposite and removes backslashes, turning \\ back into \ and dropping single backslashes.
These functions come from an era when PHP applications built SQL strings by hand. Today they are almost never the right answer. For SQL use prepared statements, for HTML use htmlspecialchars(), for JavaScript use json_encode(). The functions remain useful for generic escaping tasks, such as building a quoted string literal for a simple text format.
<?php echo addslashes("It's \"quoted\""); // It\'s \"quoted\"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
addslashes(string $string): string stripslashes(string $string): string
| Name | Description |
|---|---|
$string |
The string to escape (addslashes()) or unescape (stripslashes()). |
Return value: the converted string.
Usage notes
- Characters escaped:
',",\and the NUL byte (written as\0). Nothing else changes. - Do not use it to protect SQL. It knows nothing about the database's quoting rules or the connection's character set, and multibyte tricks have broken it in the past. Use prepared statements with PDO or mysqli.
- Not for HTML. Backslashes mean nothing to a browser. A string such as
<script>passes through untouched. stripslashes()is lossy. It removes every lone backslash, so a Windows path likeC:\temploses its separators. Only use it on text you know was escaped withaddslashes().- Magic quotes are gone. PHP used to add slashes to request data automatically (
magic_quotes_gpc); that feature was removed in PHP 5.4, so input is never pre-escaped and callingstripslashes()on$_POSTdata is a bug. - Alternatives.
addcslashes()escapes a custom set of characters and C-style escapes,quotemeta()escapes regex metacharacters, andpreg_quote()is the correct tool for building regular expressions. - Escaping twice. Applying
addslashes()repeatedly keeps adding backslashes. Escape once, at the point of use.