How to Handle Magic Quotes in PHP

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Continuing from our previous tutorial, our example assumed that your PHP server has magic quotes turned off (which is preferred).  Because PHP manual says …

“It’s preferred to code with magic quotes off and to instead escape the data at runtime, as needed.”

That is why magic quotes is DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.  Linked here is how to disable magic quotes.

Nevertheless, some old servers may still have magic quotes turned on.  PHP at runtime can determine if magic quotes is turned on or not by the function get_magic_quotes_gpc().  It returns 0 if magic_quotes_gpc is off, 1 otherwise. As of PHP 5.4.0, it will always returns FALSE.

gpc stands for “get post cookies” referring to those three request methods.  If magic_quotes is turned on, then get and post requests will cause slashes to be added before the single or double quotes.  In that case, it is preferable to remove the slashes with stripslashes().  So in our example confirmation.php page, we could write …

stripslashes if magic quotes on

stripslashes if magic quotes on

If you are sure your server does not use magic quotes, you can omit the extra code.  Otherwise, test if magic quotes is on.  If so, strip off the slashes that it added.

Speaking of quotes, let’s test our example with a complex entry like this with a combination of single and double quotes …

complex entry with single and double quotes

complex entry with single and double quotes

It works!  That’s is because we remembered to put htmlspecialchars() in our index.php page …

retrieve session variable

index.php

which by default will convert the double quotes into HTML entities "

htmlspecialchars defaults

htmlspecialchars defaults

That way, it doesn’t confuse with the double quotes that bound the value attribute.  htmlspecialchars by default does not convert the single quote because it assume most people are using double quotes around value of attributes.  It runs with the ENT_COMPAT flag by default.

So if our index.php were written as …

single quote attribute values

single quote attribute values

we would have run into problems with the complex entry.  The single quote in the entry would have terminated the remainder of the entry.

why fail

why fail

So use double quote around attribute values when you can.  If you can not, you can alter the htmlspecialchars behavior and make it convert both single and double quotes into HTML entities with the ENT_QUOTES flag as in …

ENT_QUOTES

ENT_QUOTES

That works …

 

that works

that works