When writing a SQL statement, one must be aware that the ' character is the string delimiter.
A common form of attack on websites is called a SQL Injection. In the case of a SQL Injection, the attacker is hoping that a naive programmer has not thought to deal with malicious entry in forms. For example, imagine you need to run the following SQL to check a login:
SELECT uid FROM gl_users WHERE username='someusername' AND password='somepassword'
Suppose you just took the input from a form and did nothing:
$sql = "SELECT uid FROM gl_users WHERE username='$username' AND password='$password'A malicious user could enter "someusername" for the username, but enter:
' OR '' = 'for the password, resulting in the following SQL being executed:
SELECT uid FROM gl_users WHERE username='someusername' AND password='' OR '' = ''
This will result in the user being logged in.
This is is such a common problem that the "Magic Quotes GPC" option was added.
Slashes are also automatically added to the contents of a GET, POST or COOKIE value if the Magic Quotes GPC flag is set to true on your PHP instance. For example, if you submit a form with the example above, the result would be:
SELECT uid FROM gl_users WHERE username='someusername' AND password='\' OR \'\' = \''
Which would result in a failed login.
Magic Quotes GPC becomes a problem when it comes to well coded applications, as any sensible developer will have called addslashes to escape the values prior to using them in SQL, and will use stripslashes on retrieving data from the database to put it back how it was.
addslashes adds slashes to a variable. It does this to escape quotes. So for example if you have a string:
Geeklog's API functions are rich and varied.
After a call to addslashes you will have
Geeklog\'s API functions are rich and varied.
Geeklog has a lot of code. It handles a lot of form posts and database save and load commands. The values fetched from the POST/GET/COOKIE arrays or from the database are passed in and out of numerous functions. Some of these expect non-escaped strings. Others expect escaped strings.
It currently appears to be a common source of bugs that addslashes and stripslashes are called needlessly.
It's also important to note that Geeklog has a function COM_stripslashes that calls stripslashes on the supplied variable if and only if Magic Quotes GPC is enabled.
Now, when doing code in Geeklog, the following rules should probably be followed:
- When your code is to deal with a value from $_GET, $_POST or $_COOKIE immediately load it into an internal variable after calling COM_stripslashes, this will deal correctly with the value whether or not Magic Quotes GPC is on or off.
- Immediately before using a value in SQL, addslashes to it.
- Immediately after loading a value from SQL, stripslashes on it.
There should never be another need to call addslashes or stripslashes.