Home >Backend Development >PHP Tutorial >Detailed explanation of field legality detection of new features of ThinkPHP3.1_PHP tutorial
ThinkPHP version 3.1 adds field legality detection for form submission, which can better protect data security. This feature is an important part of the 3.1 security features.
Form field legality detection can only take effect when you use the create method to create a data object. There are two ways:
1. Attribute definition
You can configure the insertFields and updateFields attributes of the model to add and edit form settings. When using the create method to create a data object, attributes that are not within the defined range will be discarded directly to avoid illegal data submission in the form.
The insertFields and updateFields attributes are set in strings (comma-separated multiple fields) or arrays, for example:
class UserModel extends Model{ protected $insertFields = array('account','password','nickname','email'); protected $updateFields = array('nickname','email'); }
The fields set should be actual data table fields and not affected by field mapping.
When using it, when we call the create method, the insertFields and updateFields attributes will be automatically recognized based on the submission type:
D('User')->create();
When using the create method to create a data object, when adding user data, fields other than 'account', 'password', 'nickname', and 'email' will be blocked. When editing, 'nickname' will be blocked. ', fields other than 'email'.
The following is a string definition method, which is also valid:
class UserModel extends Model{ protected $insertFields = 'account,password,nickname,email'; protected $updateFields = 'nickname,email'; }
2. Method calling
If you don’t want to define the insertFields and updateFields attributes, or want to call them dynamically, you can call the field method directly before calling the create method. For example, to achieve the same effect 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 actual data table fields. The field method can also use array mode.
After using field legality detection, you no longer need to worry about users injecting illegal field data when submitting forms. Obviously the second method is more flexible, choose according to your needs!