2

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?

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, in 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)");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Related: *[With “magic quotes” disabled, why does PHP/WordPress continue to auto-escape my POST data?](https://stackoverflow.com/questions/8949768)* – Peter Mortensen Dec 01 '19 at 17:47

3 Answers3

6

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
  • 3,837
  • 24
  • 32
1

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
  • 15,870
  • 11
  • 35
  • 36
  • mysql_real_escape_string() was [removed in PHP 7.0.0](https://www.php.net/mysql_real_escape_string), and magic quotes were [removed in PHP 5.4.0](https://www.php.net/manual/en/security.magicquotes.php). – Peter Mortensen Dec 01 '19 at 00:14
1

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
geowa4
  • 40,390
  • 17
  • 88
  • 107