The addslashes() function in PHP 8.5 works exactly the same as in previous versions. It is a legacy string function that adds backslashes before specific characters.
What Does addslashes() Do?
It returns a string with backslashes added before these four characters:
*Single quote ( )
*Double quote (")
*Backslash ()
*NUL (the NULL byte)
Basic Syntax
addslashes(string $string): string
Parameter:
string: The string you want to escape
Return Value:
Returns the escaped string
Basic Example
<?php
$str = "Is your name O Reilly?";
// Outputs: Is your name O Reilly?
echo addslashes($str);
?>
Example with Double Quotes
<?php
$str = addslashes( What does "yolo" mean? );
echo($str);
Output:
What does "yolo" mean??>
When to Use addslashes()?
Correct Use: Escaping characters in a string that will be evaluated by PHP.
<?php
$str = "O Reilly?";
eval("echo " . addslashes($str) . " ;");
?>
Incorrect Use (IMPORTANT): Using addslashes() to prevent SQL injection is wrong and dangerous. It does not properly escape strings for database queries. For example, MySQL requires escaping of characters like
,
, and x1a, which addslashes() does not handle.