7
23
2008
0

[PHP]格式化html代码方法htmlentities和htmlspecialchars

用户编辑上传的文字往往会包含<>""&这样的代码,如果不在后台加以处理,往往会导致不少安全问题

php自带了htmlentities和htmlspecialchars这两个方法

htmlentities 可以把用户输入的所有文字全部格式化

string htmlentities ( string string [, int quote_style [, string charset]] )


第一个参数是要格式化的字符串

第二个参数有三种情况

ENT_COMPAT Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES Will convert both double and single quotes.
ENT_NOQUOTES Will leave both double and single quotes unconverted.

     第一种会转换双引号不转换单引号
     第二种会同时转换单引号和双引号
     第三种会不转换单引号和双引号

第三个参数是设置编码格式

字符集 别名 描述
ISO-8859-1 ISO8859-1 西欧,Latin-1
ISO-8859-15 ISO8859-15 西欧,Latin-9。增加了 Latin-1(ISO-8859-1)中缺少的欧元符号、法国及芬兰字母。
UTF-8   ASCII 兼容多字节 8-bit Unicode。
cp866 ibm866, 866 DOS-特有的 Cyrillic 字母字符集。PHP 4.3.2 开始支持该字符集。
cp1251 Windows-1251, win-1251, 1251 Windows-特有的 Cyrillic 字母字符集。PHP 4.3.2 开始支持该字符集。
cp1252 Windows-1252, 1252 Windows 对于西欧特有的字符集。
KOI8-R koi8-ru, koi8r 俄文。PHP 4.3.2 开始支持该字符集。
BIG5 950 繁体中文,主要用于中国台湾。
GB2312 936 简体中文,国际标准字符集。
BIG5-HKSCS   繁体中文,Big5 的延伸,主要用于香港。
Shift_JIS SJIS, 932 日文。
EUC-JP EUCJP 日文。

 

下面是htmlspecialchars

string htmlspecialchars ( string string [, int quote_style [, string charset]] )
 

它的三个参数和htmlentities是一样的

它和htmlentities的区别就在于:

  • '&' (ampersand) becomes '&amp;'

  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.

  • ''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.

  • '<' (less than) becomes '&lt;'

  • '>' (greater than) becomes '&gt;'

可以了解到htmlspecialchars只转化上面这几个html代码,而htmlentities却会转化所有的html代码,连同里面的它无法识别的中文字符也会转化出来。

Category: PHP | Tags: php 格式化html | Read Count: 4895

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com