Sunday, April 29, 2012

SQL Insertion Update

In regards to my post on Friday about SQL Insertion, I've been playing around with it and found some interesting things. The reason I never noticed a need for the fix before is that some implementations of PHP auto correct it. They automatically add backslashes to any character that could break the input, such as apostrophes and quotations. Unfortunately, I still don't know how to figure out if that correction is in place except for manual testing.

The server hosting the CESAC site doesn't use auto correction, while the servers hosting our Purdue ICS sites do. The question will be how to figure it out with a code check so that I only correct when it's needed. I'll update this post if I figure out how.


Got it. Turns out that when using the POST method for forms, a backslash is added to the three special characters: apostrophe, quotation mark, and backslash. This is because these three characters are used in the SQL insertion statement. They are then stripped when being added to the SQL. When an implementation of PHP has magic_quotes_gpc turned on, nothing happens to these backslashes. When magic_quotes_gpc is turned off, they are removed. The way then to test is a simple if statement, which returns a 1 for on and 0 for off.

if(get_magic_quotes_gpc(void)) { }

Additionally I found a better way to fix the problem if it needs fixing. I was using str_replace before, but that only works for apostrophes and backslashes, not quotations. I found a way to fix the problem specifically however. There is a function in PHP which does exactly what is needed. It adds back slashes to each of the three characters. The code ends up being:

if(get_magic_quotes_gpc(void)) {
    $title = $_POST["title"];
    $content = $_POST["content"];
else {
    $title = addslashes($_POST["title"]);
    $content = addslashes($_POST["content"]);


No comments:

Post a Comment