[thelist] magic_quotes_gpc vs. addslashes in PHP

Andrew Clover and-evolt at doxdesk.com
Wed Jul 21 13:57:06 CDT 2004

Sarah Sweeney <mr.sanders at designshift.com> wrote:

> So what is the benefit of using addslashes() rather than magic_quotes_gpc?

Using addslashes manually grants you the opportunity to do it right, 
only adding slashes to values that are just about to be appended to a 
string literal in an SQL query. SQL literals are the only place you 
should ever need to be sticking backslashes before things.(*)

You should also manually escape <, & and " characters every time you 
copy a text value out to HTML. The function to use to do this is 
htmlspecialchars, and *not* addslashes.

The Right Thing is to keep your program's strings in plain text format 
with no special escaping internally, then do the necessary 
string-escaping at the point of exit - HTML-encoding if the text is 
going into a web page, SQL-encoding if it's going to be part of a 
database query, various other escaping schemes if it'll end up in CSS or 
JavaScript or whatever.

Using magic_quotes guarantees that your application will do this wrong. 
Applying addslashes automatically at the input phase, regardless of 
whether the submitted string is going to be sent to an SQL string 
literal or not, will lead to strange little extra slashes all over the 
place when you least expect it. In the best scenario this means Michael 
O'Hare will have to put up with being Michael O\\\\'Hare; in the worst, 
a misplaced character in a primary key, username or e-mail address can 
screw up the logic of the app and make it fall over.

Most foolish webapp authors then go further and assume that magic_quotes 
has automagically made their webapp secure, and forget to HTML-escape 
user-supplied text, resulting in cross-site-scripting holes everywhere 
and yet another advisory off to Bugtraq.

There are not many web application frameworks that make it easy to write 
scripts properly and securely. But magic_quotes is a particularly 
egregious example of PHP trying to trip the new user up with a feature 
that sounds useful but is actually harmful.

(* - amusingly, even this behaviour is wrong. The SQL92 standard says
      nothing about any special meaning to the backslash character, and
      allows the single-quote delimiter to be escaped by doubling instead
      (like in Visual Basic). However since MySQL and PostreSQL both
      assign special meaning to \ we're left with a compabitility horror
      best solved by letting the database-interfacing module deal with
      the string handling.)

Andrew Clover
mailto:and at doxdesk.com

More information about the thelist mailing list