Prefixes certain characters such as quotes and backslashes with a backslash.
What Is addslashes() in PHP?
Prefixes certain characters such as quotes and backslashes with a backslash.
Its syntax is:
addslashes(string $string): string
Parameters:
$string— Accepted as string; required argument.
Return type: string. Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.
Availability: Available in standard PHP.
Example 1: Basic Usage
<?php
echo addslashes("Don't");
Output:
Don\'t
Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.
Example 2: A Different Input
<?php
echo addslashes('He said "Hello"');
Output:
He said \"Hello\"
Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.
Practical Example: Applying It in a Program
<?php
$messages = ["It's ready", "He said 'go'"];
foreach ($messages as $message) { echo addslashes($message) . PHP_EOL; }
Output:
It\'s ready
He said \"go\"
Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.
Important Behavior and Edge Cases
- Key behavior: Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.
- Environment: Available in standard PHP.
Comparison With Related Functions
| Function | Purpose |
|---|---|
addslashes() | prefixes certain characters such as quotes and backslashes with a backslash. |
htmlspecialchars() | htmlspecialchars() encodes special HTML characters for output; addslashes() is not HTML or SQL escaping. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: Do not use addslashes() to make SQL statements safe | Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output. |
Key Takeaways
- prefixes certain characters such as quotes and backslashes with a backslash.
- Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.
- Available in standard PHP.
Summary: Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.