When to use PHP addslashes and stripslashes?

PHP addslashes is used to quotes string with slashes. These characters are single quote, double quote, backslash and NULL and basically used whenever string is passed as database query.

For example, if you want to insert name d’souza into database then we  need to quotes the string with backslashes.

$a = “d’souza”;
$sql = “insert into nametable(name) values($a)”;

The above SQL statement returns error. We need to use addslashes here to avoid such error.

$a = addslashes(“d’souza”);

In this way, we can use addslashes function.

PHP stripslashes is used to unquote’s a quoted string which is quoted with addslashes function.

But still there is a question? Above code will  run without addslashes function.

Yes, above code can run without addslashes if Magic Quotes is set to on. And in some version of PHP Magic Quotes is set on by default. But if see the PHP Manual it show warning “This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.”

What is Magic Quotes?

Magic Quotes is a process that auto magically escapes incoming data to the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime, as needed.

Here, what is incoming data is data from GET, POST and COOKIE. So, when Magic Quotes is on all these are auto magically escapes and if you do addslashes do double escapes. For example

Suppose the value of $_GET[‘data’] is d’souza

$a = $_GET[‘data’];  // if magic quotes is on then value is  d\’souza
$a = addslashes($a); // if you run addslashes function on it then value is d\\’souza

How to handle Magic Quotes?

In newer version of PHP Magic Quotes will be removed, it is recommended that do not use Magic Quotes.  Here i create two function MyInput  and MyOutput to handle magic quotes, addslashes and stripslashes.

function MyInput($str)
{
$str = trim($str);
if(get_magic_quotes_runtime())
{
return $str;
}
return addslashes($str);
}

function MyOutput($str)
{
$str = trim($str);
if(get_magic_quotes_runtime())
{
return stripslashes($str);
}
return $str;
}

In above code i use get_magic_quotes_runtime function to check  if magic quotes are set to on or off.

$a = MyInput($_GET[‘data’];

Here is my version of handling magic quotes, if this code is still need improvement then please leave a message below.