开发者

Storing values with apostrophes in the database

开发者 https://www.devze.com 2023-03-17 16:22 出处:网络
What is the industry standard inserting user input that may contain apostrophes into a database? Such an input will be displayed b开发者_如何学编程ack to users on a webpage. For example, a user update

What is the industry standard inserting user input that may contain apostrophes into a database? Such an input will be displayed b开发者_如何学编程ack to users on a webpage. For example, a user updates some field to "I'm cool". I insert it into my database with this function:

public function updateDatabase($value) {
   $value = mysql_real_escape_string($value);
   Database::instance()->query(
      'UPDATE myTable
       SET myColumn = ' . $value . '
       WHERE foo = "bar"'
   );
}

The database will now store "I\'m cool". To display this value properly and safely back to any user, I would have to clean it with this function:

public function toSafeDisplay($userGeneratedValue) {
   return stripslashes(
      htmlentities(
         $userGeneratedValue
      )   
   );
}

My concern is that doing stripslashes and htmlentities on everything I want to display on a webpage will be very processor intensive. The general concensus on StackOverflow is to not do htmlentities before inserting into the database, so that the data is as raw as possible. This would allow it to be later displayed in any medium, not just websites. So we're forced to do htmlentities at display time. Is this also true with stripslashes? Or is it possible to remove all the slashes before the apostrophes before updating the database without introducing SQL injection attacks?.


That's not how it works at all. If you escape an apostrophy going into the insert/update when you read it back into php it will NOT be escaped. If you want HTML safe data coming out of the database then make it safe before you put it in.


Notice to developers that use mysql_real_escape_string properly:

If magic_quotes_gpc is enabled, first apply stripslashes() to the data. Using this function on data which has already been escaped will escape the data twice.

If you found out that magic_quotes_gpc is set to On turn it Off in php.ini!

Check also: http://gr.php.net/manual/en/function.mysql-real-escape-string.php


The database should not store it as I\'m cool, but rather as I'm cool. The escape is to allow the apostrophe to be included as part of the data updated in myColumn. I have seen cases where a site displays I\'m cool back to the user, but that is probably a case of double-escaping.

Edit:

mysql_real_escape_string does not store slashes in the database. It escapes the value in the SQL statement. The only way you would get extra slashes in the database is if you did something equivalent to mysql_real_escape_string(mysql_real_escape_string($value)).

0

精彩评论

暂无评论...
验证码 换一张
取 消