PHP addslashes() Function

What is PHP addslashes() Function?

If you want PHP interpreter to treat a character inside a string as a literal character rather than its syntactical meaning, then, escape that character by adding a backslash (\) in front of it.

If you want to add backslashes in front of some predefined characters in a string, use PHP addslashes() function. The predefined characters of which the function adds backslashes are-

  • Single quote (‘)
  • Doublequote (“)
  • Backslash (\)
  • NULL

Syntax:

addslashes(string)

Parameters:

The Function has 1 parameter which is required-

string (Required): It specifies a string that the function will escape.

Return Values:

The function returns the escaped string.

Examples:

Example 1: Escaping a single quote

<?php
$string = "They're";
$esc_string = addslashes($string);
echo "After escaping, They're becomes: " . $esc_string;
?>

Output:

After escaping, They're becomes: They\'re

Example 2: Escaping a double quote

<?php
$string = 'Are you learning "PHP"?';
$esc_string = addslashes($string);
echo 'After escaping, Are you learning "PHP"? becomes: ' . $esc_string;
?>

Output:

After escaping, Are you learning "PHP"? becomes: Are you learning \"PHP\"?

Example 3: Escaping a backslash

<?php
$string = "C:\Users\Public";
$esc_string = addslashes($string);
echo "After escaping, C:\Users\Public becomes: " . $esc_string;
?>

Output:

After escaping, C:\Users\Public becomes: C:\\Users\\Public

Example 4: Escaping a NULL character

<?php
// Escaping a NULL character
$string = "Welcome to Schools of Web\0";
$esc_string = addslashes($string);
echo "After escaping it becomes " . $esc_string;
?>

Output:

After escaping it becomes Welcome to Schools of Web\0

Caution:

Don’t use addslashes() function to prevent SQL injection.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP addslashes() Function

addslashes() function is one of the built-in string functions. Use this function to escape those four predefined characters from a string.

Reference:

https://www.php.net/manual/en/function.addslashes.php