AaronCameron.net
An A+ for effort; the indelible, scarlet letter of the dullard.
Not a Member? - Login or Create an Account...MC Offline
Monday the 20th of October 2014 @ 07:16am
Front Page Projects Your Profile About
[]

Filed Under: Journal - General

This tutorial is a quicky to go over what magic_quotes_gpc is, why it is used and how to turn it on/off.

What are Magic Quotes?

Magic Quotes, generally speaking, is the process of escaping special characters with a '\' to allow a string to be entered into a database. This is considered 'magic' because PHP can do this automatically for you if you have magic_quotes_gpc turned on.

More specifically if magic_quotes_gpc is turned on for the copy of PHP you are using all Get, Post & Cookie variables (gpc, get it?) in PHP will already have special characters like ", ' and \ escaped so it is safe to put them directly into an SQL query.

In effect, this is the same as running addslashes() on every variable passed from the browser automatically, before you even see them.

Finding out if you're using Magic Quotes

To find out if you have magic quotes enabled, you can check the php.ini file directly or run a simple test in PHP. If you don't have administrative access to the server that your site is hosted on, skip past the php.ini example and go straight to the PHP test below.

To check the php.ini, first you have to find it. Normally, the php.ini file will be located in /usr/local/lib/ if PHP was compiled from source, or it will be in /etc/ if PHP was installed from a binary package.

Failing either of these locations, you can always cheat and run a:

0001 find / -name php.ini 2>/dev/null 

on the server to find the file in question.

After you've located the php.ini file, go ahead and run a grep against it for the option in question, like this:

0001 grep magic_quotes_gpc php.ini 

You should get back one line; I get this because I have shut off magic quotes:

0001 magic_quotes_gpc	=	Off		; magic quotes for incoming GET/POST/Cookie data 

If your line shows 'On', obviously magic quotes are enabled on your system.

If you don't have access to the php.ini file on your system, a simple test to run to find out if magic quotes is enabled or not is this simple PHP script:

0001 <form>
0002 <input type=hidden name=fish value="\">
0003 <input type="submit">
0004 <form>
0005 <?echo "<"."?"?>
0006 	if ($fish)
0007 		echo "If there is one slash here, magic quotes are off \"".
0008 			$fish.
0009 			"\"<br>"; 

Bring this script up in your browser and click the submit button. If the resulting page has one slash, magic quotes are off. If there are two, magic quotes is on. Simple.


Magic Quote Advantages

Having magic quotes turned on has some advantages. As I see them, here they are:


  • You can forget to put an addslashes() call around submitted variables and not have your SQL query fail.
  • You can skip adding slashes manually altogether to keep your code less cluttered.

Magic Quote Disadvantages

Having magic quotes turned on has lots of disadvantages. As I see them, here they are:


  • Any code using SQL written for PHP 3.x.x has to be examined to remove addSlashes calls.
  • Cases where form submissions are sent back to the browser must have the slashes removed manually with a call to stripslashes().
  • If magic quotes are ever turned off for this server, or the code is moved to a server where magic quotes isn't enabled your scripts will fail. Or worse, not fail immediately and only exhibit strange behaviour.
  • Any string operations on submitted variables, even simple 'if' statements must take into account the possiblity of slashes warping in the content.
  • Magic quotes breeds developer sloppiness. Escaping variables inserted into an SQL query (in my opinion) is something that a developer should know and think about. Not just assume everything is dandy.

Enabling / Disabling Magic Quotes

Magic quotes may be enabled or disabled in the php.ini file (see above) simply by changing the value of the magic_quotes_gpc from On to Off, or Off to On. If you do not have access to the php.ini file, inquire with the System administrator for your host and ask about having Magic quotes turned on or off. This may be done on a per-directory basis with the proper configuration.

Default Magic Quote Settings

By default magic_quotes_gpc was turned off in all 3.x.x versions of PHP. However, all PHP 4.x.x versions have this option turned on by default. To insert a little bit of personal opinion I think this was a horrible mistake because I feel that magic_quotes_gpc is problimatic in professional applications, and encourages sloppy programming behaviour. That is however just my opinion, and the FACT is that probably the version of PHP you are using has this option on by default.

Share:

Reader Comments

magic quotes

2006.05.19 03:42am
Anonymous
Can't agree more, what a horror, this magic has taken half my hair out, to figuir out.

feel my control being taken off without notice

magic code

2006.10.19 01:15am
Anonymous
you should give an example to make it understandable

  • Re: magic code

    2007.02.15 03:47pm
    Anonymous
    Whats there not to understand. If you have a string it adds slashes mostly when you don't want it to: heyimastring\\watchmagicquotesmanglemewithextraslashes\\. Then magic quotes laughs at everyone and makes your life miserable. My take on Joomla is if you want to have a difficult time with something as easy as uploading images through the admin portal don't turn them on.

    • Re (2): magic code

      2007.02.15 03:48pm
      Anonymous
      sorry i meant to say:

      My take on Joomla is if you want to have a difficult time with something as easy as uploading images through the admin portal turn them on.

still can not understand.

2007.01.10 10:35am
Anonymous
I'm now installing Joomla 1.0.12,on my host the default setting is off(because of the version is php 4?),but the joomla system recommends it need to be on.really confuzing.

  • Re: still can not understand.

    2007.01.11 09:35am
    Anonymous
    To anonymous above: "By default magic_quotes_gpc was turned off in all 3.x.x versions of PHP. However, all PHP 4.x.x versions have this option turned on by default." (it says this in the article)

    So if your host has it off by default, it could indicate that they use PHP 3.x.x, or that they have PHP 4.x.x and have changed the default behaviour.

Oh my fuckin magic quotes, GTFO! Leave me fuckin alone. I don't need your fuckin help!

2007.03.20 05:19pm
Anonymous
Magic quotes!!!! What the fuck does it imply? PHP programmers are fuckin morons who can't think for themselves? This fuckin feature has made me so fuckin angry by breaking my code, I am starting to dislike PHP and Rasmus Lerdof for insulting my intelligence. Don't hamper me by helping me too fuckin much. Any programmer with half a brain should be aware of input sanitation. If they can't do that they deserve to be hacked. Fuck magic quotes! I don't need no fuckin magic!

  • Re: Oh my fuckin magic quotes, GTFO! Leave me fuckin alone. I don't need your fuckin help!

    2007.04.06 07:53pm
    Anonymous
    This is what happens when anyone can post a comment: you get some idiots that just use the word fuck and its variants 4 times in their title and 7 times in their comment... plus they insult everyone thinking they will look smarter.

    • Re (2): Oh my fuckin magic quotes, GTFO! Leave me fuckin alone. I don't need your fuckin help!

      2007.06.12 08:14pm
      Anonymous
      did you just reply yourself?

      • Re (3): Oh my fuckin magic quotes, GTFO! Leave me fuckin alone. I don't need your fuckin help!

        2007.10.10 07:23am
        Anonymous
        This guy has a point,

        Magic quotes do more harm than good. Luckily for me I have access to the .ini file on my hosting account so have it set to off my default. However as mentioned most servers have it on my default. For these instances I always include the following code at the top of my scripts and this then allows me to code as I normally would without the abomination that is magic quotes screwing stuff up

        if(get_magic_quotes_gpc())
        {
        $var = stipslashes($_POST);
        $var2 = stripslashes($_POST);
        }

        This tests whether its turned on. if it is I automatically stripslashes then I can process my data as normal. Just remember that if you use this that you need to perform your own sanitizing. You should be doing this anyway as magic quotes only escapes quotes funnily enough!

        • Re (4): Oh my fuckin magic quotes, GTFO! Leave me fuckin alone. I don't need your fuckin help!

          2007.10.10 07:26am
          Anonymous
          Ironically this shitty coded site has just escaped half the code that I typed in above. All the developer needed to do was on escape all the vars intended to be output using htmlentities()

          As a result of this poor coding I am unable to help fellow developers with their problem as they cant seem my code!! good job Jimmysworld.. have a chocolate watch!

          • Re (5): Oh my fuckin magic quotes, GTFO! Leave me fuckin alone. I don't need your fuckin help!

            2007.10.10 11:53am
            Aaron

            Could you please email me (Aaron) with the original code so I can see what was dropped?

            Also, you can use the Preview to see how the site will mangle (yes, mangle) your comment before posting.

            Also, also, you can use [code] [/code] tags around your code to format it.

    • Re (2): Oh my fuckin magic quotes, GTFO! Leave me fuckin alone. I don't need your fuckin help!

      2008.01.08 10:37pm
      Anonymous
      Article: What is Magic Quotes GPC (magic_quotes_gpc) in PHP and the php.ini? by Jimmy on 2000.03.20 12:50pm

      - Comment: Re: Oh my fuckin magic quotes, GTFO! Leave me fuckin alone. I don't needArticle: What is Magic Quotes GPC (magic_quotes_gpc) in PHP and the php.ini? by Jimmy on 2000.03.20 12:50pm

      - Comment: Re: Oh my fuckin magic quotes, GTFO! Leave me fuckin alone. I don't need your fuckin help! by Anonymous on 2007.04.06 07:53pm your fuckin help! by Anonymous on 2007.04.06 07:53pm

Why not to use magic quotes

2007.04.26 10:50am
Anonymous
Setting magic_quotes_gpc to on does have a certain performance hit, as all GET, POST, and COOKIE (hence gpc) data has an extra processing step applied (to replace quotes with their escaped equivalents). This happens even if the data isn't used.

However, it must be said this performance hit is unlikely to be important except on the most heavily viewed sites.

The main consequence of using it is that a) any data which is inserted into a database does not need further sanitizing with addslashes(), and b) any data which is not to be inserted into a database (eg if it is to be displayed on the page) must have the escaped characters restored to normal, using stripslashes().

IMO it is better to switch it off, you do have to be more careful when inserting user-submitted data into a database, but that is really a good thing anyway. Magic quotes encourages the sort of sloppy programming that tends to cause more problems than it avoids, in the long run.

Magical Quotes

2007.07.02 08:05am
Anonymous
I agree completely! Even more frustrating, though, is when you have consciously written all of your scripts for a server with magic_quotes_gpc turned off and then, without warning, your hosting service just turns it on one Monday morning in July. You wake up and check on your site, only to find that, lo and behold, it is MAGICALLY filled with freaking backslashes because now all your data validation is being performed on data that has already been validated. Three cheers for clandestine overnight php.ini reconfigurations, and three cheers for magic_quotes_gpc!

Ironic...

2007.09.05 10:35am
Anonymous
... that you rail against magic_quotes because it takes control away from the developer on a site that is so poorly coded the w3c validator tool doesn't even attempt to validate it, and half the text is missing when displayed in IE7.

Good job.

  • Re: Ironic...

    2007.10.10 11:56am
    Aaron

    For the record, it's not ironic, it's just hypocritical. :)

    There is a huge bundle of fixes coming down the pipe to fix the site as much as possible for IE* and to have full, or near w3c compliance. IE really, really likes to render differently then everything else.

  • Re: Ironic...

    2007.10.31 11:46pm
    Anonymous
    I code to w3c standards, not Microshit standards. If my code doesn't display in IE* it's because Microshit doesn't comply to standards. I refuse to conform with everyone else because most of the browser market is IE. I use Linux, I code for Linux users who use Firefox/Iceweasel / Konqueror and all the other standard complying browsers. Just because IE is the market majority doesn't mean you have to conform--change the world, don't go with it.

    • Re (2): Ironic...

      2008.01.09 08:11pm
      Anonymous
      I agree even though I code mainly for the windows market. I get everything working fine and dandy in Firefox and it just breaks in IE. General users never understand why IE is crap though and they never will.

      As for GPC 'magic' I doubt it will be turned off in future PHP releases as it would break so many people poor coding!!!!

      • Re (3): Ironic...

        2008.03.14 07:55am
        Anonymous
        From http://us2.php.net/magic_quotes

        Magic Quotes
        This feature is DEPRECATED and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

        • Re (4): Ironic...

          2008.03.14 11:28am
          Aaron

          Huzza! Victory is ours!.... eventually.

          • Re (5): Ironic...

            2009.02.22 12:10am
            Anonymous

            The quotes are indeed magic... i.e. "Now you see them... now you don't (as of PHP 5.3.0 and PHP 6).

Fix for magic_quotes_gpc

2008.03.24 11:12am
Anonymous
I use this code at the beginning of every file (actually it's part of a set of standard functions that are in a file and is called at the beginning of every file) ever since I changed hosting companies for one that had magic_quotes_gpc 'off' to one that had it 'on'.
It only works for POST variables but could be easily changed to work for the others as well (I'm guessing)
The $debug variable is just a standard debugging tool where I can turn on all debugging from within a section of code at a time. Just set it to 1 if you want verbose information of the tool.

Any comments very welcome.

0001 // This is just a generic check for magic_quotes
0002 // If they are on they strip the slashes leaving the input unaltered
0003 	if(get_magic_quotes_gpc()){  
0004 	  if($debug){echo("Magic_quotes_gpc is on<br>");}
0005     while (list ($key, $value )  = each ($_POST)){
0006 	    // IF A VALUE WAS SELECTED	
0007 	    if(!(empty ($value)) ) {
0008 			if($debug){echo($key." - ".$value." <br>");}
0009 		  	$value = stripslashes($value);
0010 			if($debug){echo($key." - ".$value." <br>");}
0011 				$_POST[$key] = $value ;
0012 	    }
0013 	  } //while (list ($key, $value )		
0014 	}
0015 	else{
0016 	  if($debug){echo("Magic_quotes_gpc is off<br>");}
0017 	}
0018  reset($_POST); 



enjoy.

  • I agree with this article

    2008.07.24 03:20am
    Anonymous
    I agree with you jimmy. The magic quotes gpc must be turn off in php 4.xx I installed many professional scripts and all required magic quotes gpc off. If they are turned on then error 500 is showing by the server.

Magic Quotes saved my life!

2008.08.26 10:47am
Anonymous
I just love magic quotes. They make my day bearable and they always put a smile on my face. Im so thankful to everyone who writes these beautiful quotes. I love you all.

Most reliable way to find php.ini

2009.02.22 12:07am
Anonymous
It is much better to call phpinfo(); to find the location of the php.ini file.

The reason being that it guarantees that this is the version of php.ini being used by your server, as there often seems to be at least 3 php.ini files lying around on most systems ;-)

  • Re: Most reliable way to find php.ini

    2009.07.22 11:13am
    Anonymous
    I saw somewhere that
    magic_quotes_gpc = off
    is possible set using .htaccess, but there is only small "hook": many servers offers virtual folders and due that .htaccess shall be made on proper way. I met it on some so called free web hosting.

    Bosna-express last forever! Bihac 2009.

Suckage

2009.09.02 07:31am
Anonymous
Magic Quotes SUCKS! So bad even, that it has already validated your sperm before you get to squirt it out!

Yes, yet another comment that doesn't add anything useful to the conversation, but hey, I feel a lot better :)

  • Re: Suckage

    2009.11.16 08:09pm
    Anonymous

    I feel better by just reading your comment!

    • Magic quote is the cause for the slashes in the joomla ---Thanks for the superb article ..... !!!

      2011.03.22 12:19am
      Anonymous
      Thanks for the superb article of magic quotes.. the moment i read 2 to 3 lines of your article, i was over moon :) , bcoz i knew i have found my solution. I recently moved my joomla to dedicated server. Everything worked fine, apart from editing or adding new article. The slashes were getting inserted in the DB. Finally after reading your article i figured i need to enable magic quotes on my new server and i did using the below method. Even though i had access to php.ini , i used the below simple method which can be done through FTP ..Hope it helps other's who donot have server access to edit php.ini. Thanks again for this article, it saved my left over little hair :)

      \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
      The magic quotes option was introduced to help protect developers from SQL injection attacks. It effectively executes addslashes() on all information received over GET, POST or COOKIE. Unfortunately this protection isn't perfect: there are a series of other characters that databases interpret as special not covered by this function. In addition, data not sent direct to databases must un-escaped before it can be used. Because it's inconsistent and ineffective, it's not recommended that magic_quotes_gpc be enabled. Its recommended that your php scripts have programming/input filtering done so that your databases and site is protected.


      1. Login into your FTP account using an FTP program
      2. Modify your .htaccess file in the html folder and do the following:

      You can disable magic_quotes_gpc in the .htaccess file by adding:
      # Disable magic_quotes_gpc
      php_flag magic_quotes_gpc off

      If your PHP script needs magic_quotes_gpc enabled, you can enable it in the .htaccess file by adding:
      # Enable magic_quotes_gpc
      php_flag magic_quotes_gpc on

      If you get a 500 internal server error once you have put the above settings in your .htaccess file, remove them from the .htaccess file and add the following to your php file:
      To disable:
      ini_set ('magic_quotes_gpc', 0);
      To enable:
      ini_set ('magic_quotes_gpc', 1);

      \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

      • Re: Magic quote is the cause for the slashes in the joomla ---Thanks for the superb article ..... !!!

        2011.05.30 10:20am
        Anonymous
        Please check here
        http://amisoft.in/?p=214

sloppyness..

2011.07.04 03:37pm
Anonymous
= sloppiness

  • Re: sloppyness..

    2011.10.12 12:56pm
    Aaron
    Right you are. Bit of irony there.

    • Re (2): sloppyness..

      2012.05.05 07:35am
      Anonymous
      I totally agree with you
      magic_quotes_gpc should not be taken as a security feature.
      Striplashes example http://phptutorials.ws/article/turn-off-magic_quotes_gpc-on-6.html

outstanding

2012.09.10 09:51am
Anonymous
genious

©2014 Aaron Cameron