Home  >  Article  >  Backend Development  >  ThinkPHP3.1新特性之字段合法性检测详解_php实例

ThinkPHP3.1新特性之字段合法性检测详解_php实例

WBOY
WBOYOriginal
2016-06-07 17:18:39747browse

ThinkPHP3.1版增加了表单提交的字段合法性检测,可以更好的保护数据的安全性。这一特性是3.1安全特性中的一个重要部分。

表单字段合法性检测需要使用create方法创建数据对象的时候才能生效,具体有两种方式:

一、属性定义

可以给模型配置insertFields 和 updateFields属性用于新增和编辑表单设置,使用create方法创建数据对象的时候,不在定义范围内的属性将直接丢弃,避免表单提交非法数据。

insertFields 和 updateFields属性的设置采用字符串(逗号分割多个字段)或者数组的方式,例如:

class UserModel extends Model{
  protected $insertFields = array('account','password','nickname','email');
  protected $updateFields = array('nickname','email');
 }

设置的字段应该是实际的数据表字段,而不受字段映射的影响。

在使用的时候,我们调用create方法的时候,会根据提交类型自动识别insertFields和updateFields属性:

D('User')->create();

使用create方法创建数据对象的时候,新增用户数据的时候,就会屏蔽'account','password','nickname','email' 之外的字段,编辑的时候就会屏蔽'nickname','email'之外的字段。

下面是采用字符串定义的方式,同样有效:

class UserModel extends Model{
  protected $insertFields = 'account,password,nickname,email';
  protected $updateFields = 'nickname,email';
 }

二、方法调用

如果不想定义insertFields和updateFields属性,或者希望可以动态调用,可以在调用create方法之前直接调用field方法,例如,实现和上面的例子同样的作用:

在新增用户数据的时候,使用:

$User = M('User');
$User->field('account,password,nickname,email')->create();
$User->add();

而在更新用户数据的时候,使用:

$User = M('User');
$User->field('nickname,email')->create();
$User->where($map)->save();

这里的字段也是实际的数据表字段。field方法也可以使用数组方式。

使用字段合法性检测后,你不再需要担心用户在提交表单的时候注入非法字段数据了。显然第二种方式更加灵活一些,根据需要选择吧!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn