Detailed explanation of field validity detection of new features of ThinkPHP3.1

  • 2021-07-02 23:40:01
  • OfStack

ThinkPHP version 3.1 adds the validity detection of fields submitted by forms, which can better protect the security of data. This 1 feature is an important part of the 3.1 security feature.

Form field validity detection can only take effect when data objects are created by create method. There are two specific ways:

1. Attribute definition

You can configure insertFields and updateFields attributes to the model for adding and editing form settings. When using create method to create data objects, attributes that are not within the definition range will be discarded directly to avoid illegal data submission by the form.

insertFields and updateFields properties are set as strings (commas divide multiple fields) or arrays, such as:


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

The set field should be the actual datasheet field, which is not affected by the field mapping.

In use, when we call the create method, the insertFields and updateFields attributes are automatically recognized according to the commit type:


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

When using create method to create data objects, fields other than 'account', 'password', 'nickname' and 'email' will be masked when adding user data, and fields other than 'nickname' and 'email' will be masked when editing.

The following is the way defined by string, which is equally valid:


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

2. Method invocation

If you don't want to define the insertFields and updateFields properties, or if you want to call them dynamically, you can call the field method directly before calling the create method, for example, to achieve the same function as the above example:

When adding user data, use:


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

When updating user data, use:


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

The fields here are also the actual data table fields. The field method can also use array mode.

With field validity detection, you no longer need to worry about users injecting illegal field data when submitting forms. Obviously, the second way is more flexible. Choose according to your needs!


Related articles: