PHP “Magic Quotes” Explained

  • Avinash
  • 4
  • Sep 13, 2011
  • Tutorial

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 addslashes() 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.

magic_quotes_gpc = Off magic_quotes_runtime = Off magic_quotes_sybase = Off
  magic_quotes_gpc = Off

  magic_quotes_runtime = Off

  magic_quotes_sybase = Off
2) Disable using .htaccess

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

php_flag magic_quotes_gpc Off # OR php_value magic_quotes_gpc Off
  php_flag magic_quotes_gpc Off
  # OR
  php_value magic_quotes_gpc Off
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.

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"); }
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");

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

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: