tags:

views:

518

answers:

3

Hello,

The code below allows the user to enter in a phrase in plain English, which is then added to a database as "$site." If the user enters in an apostrophe, the phrase is stored with a backslash in front of the apostrophe. How can I get the variable "$site" to be added to the database without backslashes in front of apostrophes?

Thanks in advance,

John

print   "<div class=\"siteadd\">
     <form action='process.php?find=$find1' method='post'>
     Add a book to this topic: <input name='site' type='text' size='50'>
     <input type='submit' value='Submit'>
     </form> 
     </div>";

Then, on process.php:

$site = str_replace($remove_array, "", $_POST['site']);
$site = strtolower($site);
$site = mysql_real_escape_string($site);
$illegal = array("/", "\"");
$site = str_replace($illegal, '', $site);

mysql_query("INSERT INTO `$find` VALUES (NULL, '$site',1,0)");
+1  A: 

The call to mysql_real_escape_string() is probably the reason (http://us2.php.net/mysql_real_escape_string), but you might also have Magic Quotes enabled on your server (http://php.net/manual/en/security.magicquotes.php).

Brock Boland
+1  A: 

use mysqli::prepare, then use bind_param on the resulting mysqli_stmt. This will prevent other types of sql injection as well.

geowa4
+1  A: 

I assume the backslash is added by PHP for security reasons. Read more about magic quotes. And since you’re using the proper function to escape strings passed to mysql queries, you don’t have to rely on PHP’s dummy escaping.

At the beginning of the script, check if magic_quotes are on, and if so, remove the slashes:

if (get_magic_quotes_gpc()) {
    function stripslashes_deep($value)
    {
        $value = is_array($value) ?
                    array_map('stripslashes_deep', $value) :
                    stripslashes($value);

        return $value;
    }

    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
    $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}

BTW, in your code, $find variable comes from an untrusted source and should be escaped/filtered as well.

Maciej Łebkowski
Thanks... this works. And I added "mysql_real_escape_string" to $find.
You should check if $find is on your whitelist. You don’t want to let anyone add data to *any* table in your database, do you?
Maciej Łebkowski