TP5框架安全机制实例分析
这篇文章主要介绍了TP5框架安全机制,结合实例形式分析了thinkPHP5防止SQL注入以及表单合法性检测的安全性操作技巧,需要的朋友可以参考下
本文实例讲述了TP5框架安全机制。分享给大家供大家参考,具体如下:
防止sql注入
1、查询条件尽量使用数组方式,具体如下:
1 2 3 4 5 6 7 | $wheres = array (); $wheres [ 'account' ] = $account ; $wheres [ 'password' ] = $password ; $User ->where( $wheres )->find(); |
2、如果必须使用字符串,建议使用预处理机制,具体如下:
1 2 3 | $User = D( 'UserInfo' ); $User ->where( 'account="%s" andpassword="%s"' , array ( $account , $password ))->find(); |
3、可以使用PDO方式(绑定参数),因为这里未使用PDO,所以不罗列,感兴趣的可自行查找相关资料。
表单合法性检测
1、配置insertFields和updateFields属性
1 2 3 4 5 6 7 8 9 10 11 12 13 | class UserInfoModelextends Model { // 数据表名字 protected $tureTableName = 'user' ; // 配置插入和修改的字段匹配设置(针对表单) protected $insertFields = array ( 'name' , 'sex' , 'age' ); protected $updateFields = array ( 'nickname' , 'mobile' ); } |
上面的定义之后,当我们使用了create方法创建数据对象后,再使用add方法插入数据时,只会插入上面配置的几个字段的值(更新类同),具体如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // 用户注册(示意性接口:插入) public function register() { // ... // 使用Model的create函数更安全 $User = D( 'UserInfo' ); $User ->create(); $ID = $User ->add(); if ( $ID ) { $result = $User ->where( 'id=%d' , array ( $ID ))->find(); echo json_encode( $result ); } // ... } |
2、使用field方法直接处理
1 2 3 4 5 6 7 | // 插入 M( 'User' )->field( 'name,sex,age' )->create(); // 更新 M( 'User' )->field( 'nickname,mobile' )->create(); |