addslashes() - add a backslash to PHP string special characters

Posted on Aug 17, 2022

Learn how to use the addslashes() function in PHP

Photo from Unsplash

The PHP addslashes() function is used to add backslashes to these special characters:

  1. single quote (')
  2. double quote (")
  3. backslash (\)
  4. NULL value
addslashes(string $string): string

addslashes() accepts a string as its parameter and will return that string with backslashes added.

This function is commonly used to escape the special characters from getting evaluated.

For example:

$str = 'PHP is a "server-side" programming language';

echo addslashes($str);
// 👆 PHP is a \"server-side\" programming language

While this function can be used to prepare your string for database storage or query, it’s not recommended to use it.

This is because databases have their own specific escaped functions, like mysql_real_escape_string for mySQL and pg_escape_string() for PostgreSQL.

addslashes() doesn’t make your query string safe for use as database query, as it only escapes the four characters mentioned above.

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.