Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

php - Decoding mysql_real_escape_string() for outputting HTML

I'm trying to protect myself from sql injection and am using:

mysql_real_escape_string($string);

When posting HTML it looks something like this:

<span class="&quot;className&quot;">
<p class="&quot;pClass&quot;" id="&quot;pId&quot;"></p>
</span>

I'm not sure how many other variations real_escape_string adds so don't want to just replace a few and miss others... How do I "decode" this back into correctly formatted HTML, with something like:

html_entity_decode(stripslashes($string));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The mysql_real_escape_string() manual page tells you which characters are escaped:

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: x00, , , , ', " and x1a.

You could successfully reverse the escaping by replacing those escaped characters with their unescaped forms.

mysql_real_escape_string() shouldn't be used to sanitize HTML though... there's no reason to use it before outputting web page data. It should only be used on data that you're about to put into the database. Your sanitization process should look something like this:

Input

  1. Accept user input from a form or HTTP request
  2. Create database query using mysql_real_escape_string()

Output

  1. Fetch data out of the database
  2. Run any user-defined data through htmlspecialchars() before printing

Using a different database driver such as MySQLi or PDO will allow you to use prepared statements, which take care of escaping most inputs for you. However, if you can't switch or take advantage of those, then definitely use mysql_real_escape_string()... just only use it before inserting data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...