解码mysql_real_escape_string()以输出HTML [英] Decoding mysql_real_escape_string() for outputting HTML

查看:76
本文介绍了解码mysql_real_escape_string()以输出HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试保护自己免受sql注入的侵扰,并且正在使用:

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

mysql_real_escape_string($string);

发布HTML时,它看起来像这样:

When posting HTML it looks something like this:

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

我不确定real_escape_string添加了多少其他变体,所以不想只替换一些而错过其他...我如何将其解码"回正确格式的HTML,例如:

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));

推荐答案

mysql_real_escape_string()手册页告诉您哪些字符已转义:

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

mysql_real_escape_string()调用 MySQL的库函数 mysql_real_escape_string,其中 在前面加上反斜杠 字符:\ x00,\ n,\ r,\,',和 \ x1a.

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

通过将那些转义的字符替换为其未转义的形式,您可以成功地逆转转义.

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

mysql_real_escape_string()清理HTML……在输出网页数据之前没有理由使用它.它仅应用于将要放入数据库中的数据.您的消毒过程应如下所示:

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:

输入

  1. 接受来自表单或HTTP请求的用户输入
  2. 使用mysql_real_escape_string()
  3. 创建数据库查询
  1. Accept user input from a form or HTTP request
  2. Create database query using mysql_real_escape_string()

输出

  1. 从数据库中获取数据
  2. 在打印前通过htmlspecialchars()运行任何用户定义的数据
  1. Fetch data out of the database
  2. Run any user-defined data through htmlspecialchars() before printing

使用其他数据库驱动程序,例如 MySQLi

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.

这篇关于解码mysql_real_escape_string()以输出HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆