PHP addslashes() Function

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Functions

What You’ll Learn

The addslashes() function automatically adds backslashes before single quotes, double quotes, backslashes, and the NUL byte. It is one of the simplest PHP tools for escaping strings when you need standard quote protection without choosing characters manually.

01

Four Characters

Escapes ', ", \, and NUL.

02

One Parameter

Just pass the input string.

03

Returns String

Original stays unchanged.

04

stripslashes()

Reverse the escaping.

05

User Input

Prepare text for storage.

06

vs addcslashes()

Automatic vs selective.

Definition and Usage

In PHP, addslashes() is a built-in string function that returns a copy of the input string with a backslash inserted before each occurrence of a single quote ('), double quote ("), backslash (\), or NUL byte. For example, "It's a \"quote\" test" becomes It\'s a \\\"quote\\\" test after escaping.

💡
Beginner Tip

addslashes() is not a substitute for prepared statements in database code. Use it to understand string escaping, or in legacy contexts—but for SQL, always prefer PDO/MySQLi prepared statements. For HTML output, use htmlspecialchars().

📝 Syntax

The addslashes() function takes a single string parameter:

PHP
string addslashes(string $str)

Parameters

  • $str — the input string to escape.

Characters Escaped

  • Single quote (') → \'
  • Double quote (") → \"
  • Backslash (\) → \\
  • NUL byte\0

Return Value

Returns a new escaped string. The original $str is not modified.

⚡ Quick Reference

InputResult
"It's fine"It\'s fine
'Say "hello"'Say \"hello\"
"C:\temp"C:\\temp
"No specials"No specials (unchanged)
"""" (empty)
Basic
addslashes($str)

Escape standard characters

Reverse
stripslashes($str)

Remove added slashes

Assign
$safe = addslashes($input)

Store escaped copy

Compare
addcslashes($s, "'")

Selective escaping

Examples Gallery

Run these examples in any PHP 7+ environment. Each one shows a common pattern beginners encounter with addslashes().

📚 Getting Started

Start with the classic example: escaping a single quote inside a string.

Example 1 — Escape a Single Quote

The most straightforward use case: add a backslash before an apostrophe so the string can be safely embedded in SQL-like contexts or single-quoted literals.

PHP
<?php
$original = "This is a string with a single quote (').";
$escaped  = addslashes($original);

echo "Original: $original\n";
echo "Escaped:  $escaped\n";
?>

How It Works

  • $original stays unchanged; addslashes() returns a new string.
  • Only the apostrophe character is escaped in this input—no quotes or backslashes appear elsewhere.
  • The backslash tells PHP (or other parsers) to treat the quote as a literal character.

Example 2 — All Four Escaped Characters

See how addslashes() handles every character in its default set within one string.

PHP
<?php
$text = 'She said "Hi" and it\'s a path: C:\data\\';

echo addslashes($text) . "\n";
?>

How It Works

  • Double quotes become \".
  • Single quotes become \'.
  • Each backslash becomes \\.
  • Letters, digits, and spaces pass through untouched.

📈 Practical Patterns

Real-world scenarios where quote escaping matters.

Example 3 — Escaping Windows File Paths

Backslashes in file paths are a common reason to call addslashes() when building strings programmatically.

PHP
<?php
$path = "C:\Users\Mari\Documents\report.pdf";
$safe = addslashes($path);

echo "Original: $path\n";
echo "Escaped:  $safe\n";
?>

How It Works

Every backslash in the path gets doubled. This is useful when embedding a path inside a single-quoted SQL string or a JSON-like structure in older PHP code.

Example 4 — Reversing with stripslashes()

When you need the original text back, use stripslashes() to remove the backslashes addslashes() added.

PHP
<?php
$userComment = "O'Brien said \"great job\"!";
$stored      = addslashes($userComment);
$restored    = stripslashes($stored);

echo "Stored:   $stored\n";
echo "Restored: $restored\n";
echo "Match:    " . ($restored === $userComment ? "yes\n" : "no\n");
?>

How It Works

stripslashes() is the inverse of addslashes(). After storing escaped data, call it before displaying the original text to the user—but never skip proper HTML encoding when outputting to a web page.

Example 5 — addslashes() vs addcslashes()

Compare automatic escaping with the selective approach from addcslashes().

PHP
<?php
$text = 'Price: $9.99 (50% off)';

echo "addslashes:\n";
echo addslashes($text) . "\n\n";

echo "addcslashes (digits only):\n";
echo addcslashes($text, "0-9") . "\n";
?>

How It Works

This string has no quotes or backslashes, so addslashes() leaves it unchanged. addcslashes() with 0-9 escapes every digit instead. Choose addslashes() when you need the standard four-character set; choose addcslashes() when you need custom control.

🚀 Common Use Cases

  • Legacy database code — understand how older PHP apps escaped strings before prepared statements were standard.
  • String serialization — prepare text with quotes for storage in flat files or logs.
  • Debugging escaping — inspect how PHP inserts backslashes before moving to safer tools.
  • Form data handling — escape user comments that contain apostrophes or quotation marks.
  • Reading third-party code — recognize addslashes() / stripslashes() pairs in maintained projects.

🧠 How addslashes() Works

1

PHP reads the input string

You pass a single $str argument—from a variable, literal, or user input.

Input
2

Special characters get a backslash

PHP scans each character. When it finds ', ", \, or NUL, it inserts \ before it.

Transform
3

A new string is returned

The original string is left untouched. Assign the result to a variable or pass it to another function.

Output
=

Escaped string ready

Quotes and backslashes are prefixed with backslashes for safe embedding or storage.

📝 Notes

  • addslashes() is not charset-aware and is not a complete SQL injection defense.
  • Always use prepared statements (PDO/MySQLi) for database queries in modern PHP.
  • For HTML output, use htmlspecialchars() with ENT_QUOTES and UTF-8—not addslashes().
  • PHP removed magic_quotes in PHP 5.4.0; you must call escaping functions explicitly when needed.
  • Pair with stripslashes() only when you intentionally need to undo escaping—avoid double-escaping.

Conclusion

The addslashes() function is a straightforward way to escape the four most common special characters in PHP strings: single quotes, double quotes, backslashes, and NUL. It requires no charlist and returns a new string every time.

Use it to learn how PHP string escaping works and to read legacy code—but for production security, rely on prepared statements for databases and htmlspecialchars() for web output.

💡 Best Practices

✅ Do

  • Use prepared statements for all database interactions
  • Use htmlspecialchars() when outputting user data to HTML
  • Pair with stripslashes() only when you need to reverse escaping
  • Understand what characters addslashes() affects before using it
  • Prefer addcslashes() when you need selective character escaping

❌ Don’t

  • Rely on addslashes() as your primary SQL injection defense
  • Call addslashes() on data that is already escaped (double escaping)
  • Output escaped strings directly to HTML without proper encoding
  • Assume addslashes() and addcslashes() behave the same
  • Use addslashes() when json_encode() or prepared statements are the right tool

Key Takeaways

Knowledge Unlocked

Five things to remember about addslashes()

Use these points whenever you escape characters in PHP strings.

5
Core concepts
🔄 02

One Argument

addslashes($str)

Syntax
🛠 03

stripslashes()

Reverses escaping.

Companion
🔒 04

Not for SQL

Use prepared statements.

Security
05

vs addcslashes()

Automatic vs selective.

Compare

❓ Frequently Asked Questions

addslashes() returns a new string with a backslash inserted before single quotes, double quotes, backslashes, and the NUL (null) byte. It is PHP's built-in way to escape the most common special characters in plain strings.
string addslashes(string $str). You pass one string argument and receive an escaped copy. The original string is never modified.
Exactly four: single quote ('), double quote ("), backslash (\), and the NUL byte. No other characters are affected.
addslashes() always escapes the same four characters automatically. addcslashes() lets you choose any characters via a charlist argument. Use addslashes() for standard quote escaping; use addcslashes() when you need selective control.
No. Modern PHP applications should use prepared statements (PDO or MySQLi) for database queries. addslashes() alone does not provide reliable protection against SQL injection in all contexts.
Use stripslashes(), the companion function that removes backslashes before the characters addslashes() escapes. It reverses the escaping performed by addslashes().

Explore More PHP String Functions

Continue with bin2hex(), htmlspecialchars(), and the rest of the string function reference.

Next: bin2hex() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful