Main Content

PHP Magic Quotes

Archive - Originally posted on "The Horse's Mouth" - 2005-08-22 19:57:29 - Graham Ellis

Do you want to read a string from a form and save it into a database? "Easy" you might say ... and indeed it is ... but if you just take the exact characters that were entered into the form and embed them in your SQL, you're laying yourself open to an injection attack. That's where a user enters a string that includes quotes, which are used as delimiters by SQL commands.

Early / more advanced / sophisticated users of PHP know of this risk and use the addslashes function before they place user inputs into SQL strings. But with huge growing popularity and use by beginners and more casual programmers, there was too much risk of PHP getting itself a bad name for insecure systems. So "Magic Quotes" were introduced. With Magic Quotes, the input arrays $_GET, $_POST, $_COOKIE and $_REQUEST are all encoded with extra \ characters in front of any user entered quote character ...thus making the input directly and safely transferreable into an SQL table - but at the expense of it appearing on the screen if the programmer prints it back out. See the example picture provided ....

For the sake of compatibility with existing code (and to appease the people who were quite happy to carefully add slashes all around), Magic Quotes were added to the list of configurable options in PHP and to this day it's probably one of the first things that I look at when I'm using a new host. Personally, I don't care which way it is set but I regret the incompatibility it can cause as an application is moved between servers.

Want to make your application portable? You can - since you can check the setting of the magic_quotes_gpc variable from your script, and if it is set, use stripslashes to regularise your input. We've a demo showing how you can do this on a single input field ** Link ** and there's a further discussion and more examples at the PHP manual site ** Link **