Tutorial

PHP “Magic Quotes” Explained

First of let me say that Magic Quotes is deprected from the PHP 5.3 and will be removed completely from the PHP 6. But as a developer you might face a situation when you have to work on application which runs on older version of PHP with some older functionality like rely on Magic Quotes.

So let’s get into Magic Quotes in PHP.

What is Magic Quotes?

Magic Quotes is the process which escape the incoming data to the PHP script like $_POST, $_GET. But it is recommeded to code with he magic quotes off.

When magic quotes is enabled then it will escape single quote(‘), Double Quote(“), backslash(\) and NULL by placing backslash in front of these characters. This is same as performing [code]addslashes()[/code] on any string.

So whenever your user post the form with value like avinash’s name then you will get avinash\’s name in $_POST value.

Good to use or not?

There is no reason which shows any benefit for using Magic Quotes. Hence it is deprecated from PHP 5.3.0.

So it not a good practice to use the magic Quotes then how to disable this? Let’s have a look at below section.

Disable Magic Quotes

There ae several ways to disable the Magic Quotes.

1) Disable using PHP.ini

You can set below setting from php.ini file.

[cc lang=”apache”]
magic_quotes_gpc = Off

magic_quotes_runtime = Off

magic_quotes_sybase = Off
[/cc]

2) Disable using .htaccess

Place below code in your .htaccess file if you don’t have access to php.ini file.

[cc lang=”apache”]
php_flag magic_quotes_gpc Off
# OR
php_value magic_quotes_gpc Off
[/cc]

3) Remove the effect of Magic Quotes using PHP

Sometimes disabling magic quotes through .htaccess will not affect. In that case you can have below code in top of all php code. So below code will remove shashes added by Magic Quotes.

[cc lang=”php”]
if (get_magic_quotes_gpc())
{
function remove_slash(&$value)
{
$value = stripslashes($value);
}
array_walk_recursive($_GET, “remove_slash”);
array_walk_recursive($_POST, “remove_slash”);
array_walk_recursive($_COOKIE, “remove_slash”);
array_walk_recursive($_REQUEST, “remove_slash”);
}
[/cc]

Note: Magic Quotes is Deprected in PHP 5.3.0 and will be removed from PHP 6.0

Shares:

Leave a Reply

Your email address will not be published. Required fields are marked *