您的位置:首页 > 编程语言 > PHP开发

YII 安全

2014-04-24 15:06 204 查看
一,防 sql 注入

SQL 有二个方法 ,PDO 和 AR

AR 自带有防SQL 注入的。

pdo 的用法:

绑定参数

要避免 SQL 注入攻击 并提高重复执行的 SQL 语句的效率, 你可以 "准备(prepare)"一条含有可选参数占位符的 SQL 语句,在参数绑定时,这些占位符将被替换为实际的参数。

参数占位符可以是命名的 (表现为一个唯一的标记) 或未命名的 (表现为一个问号)。调用 CDbCommand::bindParam() 或 CDbCommand::bindValue() 以使用实际参数替换这些占位符。 这些参数不需要使用引号引起来:底层的数据库驱动会为你搞定这个。 参数绑定必须在 SQL 语句执行之前完成。

// 一条带有两个占位符 ":username" 和 ":email"的 SQL

$sql="INSERT INTO tbl_user (username, email) VALUES(:username,:email)";

$command=$connection->createCommand($sql);

// 用实际的用户名替换占位符 ":username"

$command->bindParam(":username",$username,PDO::PARAM_STR);

// 用实际的 Email 替换占位符 ":email"

$command->bindParam(":email",$email,PDO::PARAM_STR);

$command->execute();

// 使用新的参数集插入另一行

$command->bindParam(":username",$username2,PDO::PARAM_STR);

$command->bindParam(":email",$email2,PDO::PARAM_STR);

$command->execute();

方法 bindParam() 和 bindValue() 非常相似。唯一的区别就是前者使用一个 PHP 变量绑定参数, 而后者使用一个值。对于那些内存中的大数据块参数,处于性能的考虑,应优先使用前者。

------------------------

即,把SQL 的模板和变量值分二次传到数据库服务器处理。

模板是: select * from table where id = ? and name = ?

值:parameter

type: field_type_var_string

value: 21

type: field_type_var_string

value: zhangsan

二,防 XSS 攻击

CHmtl:encode()

把特殊的字符编码为HTML实体。

/**

* Encodes special characters into HTML entities.

* The {@link CApplication::charset application charset} will be used for encoding.

* @param string $text data to be encoded

* @return string the encoded data

* @see http://www.php.net/manual/en/function.htmlspecialchars.php
*/

public static function encode($text)

{

return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);

}

// charset 缺省为 utf-8



CHtmlPurifier::purify()

通过移除恶意代码对HTML内容进行净化。

/**

* Purifies the HTML content by removing malicious code.

* @param string $content the content to be purified.

* @return string the purified content

*/

public function purify($content)

{

$purifier=new HTMLPurifier($this->options);

$purifier->config->set('Cache.SerializerPath',Yii::app()->getRuntimePath());

return $purifier->purify($content);

}


http://htmlpurifier.org/ http://htmlpurifier.org/demo.php
HTML Purifier是基于php 5所编写的HTML过滤器,支持自定义过滤规则,还可以把不标准的HTML转换为标准的HTML,是WYSIWYG编辑器的福音。

使用HTML Purifier的要求

php 5+

iconv

bcmath

tidy
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: