开发者

PHP & MySQL question user submitted data?

开发者 https://www.devze.com 2022-12-24 17:41 出处:网络
I was wondering how开发者_StackOverflow中文版 can I allow users to enter HTML and CSS to the there profiles safely using PHP and MySQL like they do on MySpace.You certainly want to carefully sanitize

I was wondering how开发者_StackOverflow中文版 can I allow users to enter HTML and CSS to the there profiles safely using PHP and MySQL like they do on MySpace.


You certainly want to carefully sanitize the data and limit it to a set of "unharmful" statements. E.g. http://htmlpurifier.org/ can help you with that.

HTML Purifier is a standards-compliant HTML filter library written in PHP. HTML Purifier will not only remove all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive whitelist, it will also make sure your documents are standards compliant

When you put the data into the database use prepared statements or carefully escape the data.


There are at least two things to consider :

  • safely saving the HTML data into the database
  • safely outputing the HTML data on the page.


For the first point, you must avoid SQL injections.

This can be done by escaping your string data, before injecting it into your insert query, with functions such as mysql_real_escape_string, mysqli_real_escape_string, or PDO::quote, depending on the API you are using.

Also, you might be interested by Prepared Statements ; see PDO::prepare, or mysqli_prepare.


For the second point, what matters is only allowing HTML tags and attributes that you consider as safe.

This can be done using a tool such as HTMLPurifier, to filter out all bad/non-accepted tags and attributes, and only keep the subset you whish to allow.


For example, if you consider the following HTML input :

<p>hello, world !</p>
<script type="text/javascript">alert('bad');</script>
<strong>this is <em>some text</strong></em>

HTMLPurifier will transform / purify it to :

<p>hello, world !</p>
<strong>this is <em>some text</em></strong>

Note that :

  • the <script> tag has been removed
  • the <em> and <strong> tags have been put back in the right order, making the HTML XHTML valid.
0

精彩评论

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

关注公众号