PHP addslashes() Function

Quick summary: The PHP addslashes() function returns a string with backslashes before characters that need to be escaped.

PHP addslashes() Syntax

addslashes(string $string): string
PHP

PHP addslashes() Basic examples

echo addslashes("O'Reilly");
PHP
Output:
O\'Reilly

Escapes single quotes.

echo addslashes('He said "Hello"');
PHP
Output:
He said \"Hello\"

Escapes double quotes.

echo addslashes("Backslash \\");
PHP
Output:
Backslash \\\\

Escapes backslashes.

PHP addslashes() Real-world usage

$input = "John's book";
$safe = addslashes($input);
echo $safe;
PHP
Output:
John\'s book

Prepares string for basic storage or logging.

PHP addslashes() Edge cases

echo addslashes("");
PHP

Empty string remains empty.

PHP addslashes() Common mistakes

Using addslashes() for SQL protection

addslashes() is NOT safe for SQL injection prevention.

Incorrect
$sql = "SELECT * FROM users WHERE name = '" . addslashes($name) . "'";
Correct
$stmt = $pdo->prepare("SELECT * FROM users WHERE name = ?");

Always use prepared statements instead of addslashes().

PHP addslashes() Frequently Asked Questions

What does addslashes() do?

Escapes quotes and special characters.

Use case?

Basic escaping.

Is it safe for SQL?

No, use prepared statements.

Common mistake?

Using for security.

Characters escaped?

Quotes, backslashes, null.

Performance?

Fast.

Alternative?

PDO prepared statements.

Does it modify string?

Returns new string.

Safe?

Not for SQL injection.

Handles UTF-8?

Yes.

Best practice?

Avoid for DB queries.

Used in legacy code?

Yes.

PHP addslashes() Related PHP Functions