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

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.

Take your skills to the next level ⚡️

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

No spam. Unsubscribe anytime.