Table of Contents
Create method and automatic token verification example tutorial in ThinkPHP, thinkphpcreate
ThinkPHP: What is the use of the create() method?
thinkphp automatic verification shows this error message: What does _TOKEN_ERROR_ mean?
Home Backend Development PHP Tutorial Create method and automatic token verification example tutorial in ThinkPHP, thinkphpcreate_PHP tutorial

Create method and automatic token verification example tutorial in ThinkPHP, thinkphpcreate_PHP tutorial

Jul 13, 2016 am 10:20 AM
create thinkphp token verify

Create method and automatic token verification example tutorial in ThinkPHP, thinkphpcreate

This article shows the implementation of the create method and automatic token verification in ThinkPHP in the form of an example. The specific steps are as follows:

1. Data table structure

The user table structure is as follows:

id username password

2. View template part

aoliHomeTpldefaultUsercreate.html page is as follows:

<form action="__URL__/addit" method="post">
 <input type="text" name="id" />
 <input type="text" name="username" />
 <input type="password" name="password" />
 <input type="submit" name="sub" value="提交" />
</form>

Copy after login

3. Action part:

aoliHomeLibAction.php page is as follows:

<&#63;php
 class UserAction extends Action {
  function create(){
     $this->display();   
   }
   
   function addit(){
     //向表user中添加表单内容
     $user=M('user');
     $user->create();
     $user->add();
     //判断是否存在令牌验证
     if(!$user->autoCheckToken($_POST)){
       dump('no'); 
     }else{
       dump('yes');   
     }
 }
&#63;>

Copy after login

1. Before operating the data submitted by the form, we often need to manually create the required data, such as the form data submitted above:

 //实例化User模型
  $user=M('user');
 
 //获取表单的POST数据
  $data['username']=$_POST['username']
  $data['password']=$_POST['password']
 
 //写入到数据库
   $user->data($data)->add();
Copy after login

Attachment: Data objects created using the data method will not be automatically verified and filtered, and need to be processed by yourself. If you just want to simply create a data object and do not need to complete some additional functions, you can simply use the data method. Create data objects.

2. ThinkPHP can help us quickly create data objects. The most typical application is to automatically create data objects based on form data. The data object created by the create method is stored in memory and is not actually written to the database.

   //实例化user模型
    $user=M('user');
  
   //根据表单提交的POST数据创建数据对象,并保存在内存中,可以通过dump($user)查看
    $user=create();

   //把创建的数据对象写入数据库中
    $user->add();

Copy after login

3. The create method supports creating data objects from other ways, such as from other data objects or arrays, etc.

   $data['name']='ThinkPHP';
   $data['eamil']='ThinkPHP@gmail.com';
   $user->create($data);

   甚至还可以支持从对象创建新的数据对象,如从user数据对象创建新的member数据对象
   $user=M('user');
   $user->find(1);
   $member=M('member');
   $member->create($user);

Copy after login

4. While creating the data object, the create method also completes some meaningful work, including token verification, automatic data verification, field type search, automatic data completion, etc.

Therefore, the token verification, automatic verification and automatic completion functions we are familiar with must actually use the create method to take effect.

5. Token verification:

Function: It can effectively prevent remote submission of forms and other security protections.

Add the following configuration to config.php:

   'TOKEN_ON'   =>  true, //是否开启令牌验证
   'TOKEN_NAME'  =>  'token',// 令牌验证的表单隐藏字段名称
   'TOKEN_TYPE'  =>  'md5',//令牌验证哈希规则

Copy after login

Auto token will put an md5 encrypted string into the current SESSION session. And insert this string into the form of a hidden field before the form. This string appears in two places, one is in the SESSION and the other is in the form. When you submit the form, the first thing the server does is compare the SESSION information. If it is correct, the form is allowed to be submitted, otherwise it is not allowed to be submitted.

Looking at the source code of create.html, you will see that there is an automatically generated hidden field before the end mark of the form

<input type="hidden" name="token" value="eef419c3d14c9c93caa7627eedaba4a5" />
Copy after login

(1) If you want to control the location of the hidden field, you can manually add the {__TOKEN__} mark to the form page, and the system will automatically replace it when outputting the template.

(2) If form token verification is turned on, individual forms do not need to use token verification
function, you can add {__NOTOKEN__} to the form page, and the system will ignore the token verification of the current form.

(3) If there are multiple forms on the page, it is recommended to add the {__TOKEN__} identifier and ensure that only one form requires token verification.

(4) If you use the create method to create a data object, form verification will be automatically performed at the same time. If this method is not used, you need to manually call the autoCheckToken method of the model for form verification.

if (!$User->autoCheckToken($_POST)){
// 令牌验证错误
}
Copy after login

I hope the examples shown in this article will be helpful to everyone’s ThinkPHP programming design.

ThinkPHP: What is the use of the create() method?

1. The create method can process the data submitted by POST (automatically encapsulate the data instance through the corresponding relationship between the field name in the table and the name submitted by the form). For example, there is a field named "username" in the user table. If the form There is an , then $User = M('User'); $data = $User->create(); echo $data['username'] ; will output "Xiao Ming", you don't need to use $_POST['username'] to receive it.
2. Use the create method to perform token verification on the form to prevent repeated submission of the form.
3. The data can be automatically verified, but the premise is that you must manually create a UserModel.class.php file in the Model folder and add verification rules in it
protected $_validate = array(
array( 'username','require','Username must be', 1),
);
4. Fields can be assigned values ​​automatically, but a UserModel.class.php file must be manually created in the Model folder , add
protected $_auto = array(
array('create_time','time',self::MODEL_INSERT,'function'),
);
Then the user's registration time will be Automatically assign the value to the current time

Attached is the source code of the create method:
/**
* Create a data object but do not save it to the database
* @access public
* @param mixed $data Create data
* @param string $type status
* @return mixed
*/
public function create($data='',$type='') {
/ / If no value is passed, the POST data is taken by default
if(empty($data)) {
$data = $_POST;
}elseif(is_object($data)){
$data = get_object_vars ($data);
}
// Verify data
if(empty($data) || !is_array($data)) {
$this->error = L('_DATA_TYPE_INVALID_ ');
return false;
}

// Check field mapping
$data = $this->parseFieldsMap($data,0);

/ / Status
$type = $type?$type:(!empty($data[$this->ge...The rest of the text>>

thinkphp automatic verification shows this error message: What does _TOKEN_ERROR_ mean?

The new version of ThinkPHP has a built-in form token verification function, which can effectively prevent remote submission of forms and other security protections.

Configuration parameters related to form token verification are: 'TOKEN_ON'=>true, // Whether to enable token verification 'TOKEN_NAME'=>'__hash__', // Form hidden fields for token verification Name 'TOKEN_TYPE'=>'md5', //The default token hash verification rule is MD5. If the form token verification function is turned on, the system will automatically generate a hidden field named TOKEN_NAME in the template file with the form. , its value is a hash string generated in TOKEN_TYPE mode, used to implement automatic token verification of the form. The automatically generated hidden field is located before the form end mark. If you want to control the position of the hidden field, you can manually add the mark on the form page, and the system will automatically replace it when outputting the template. If form token verification is turned on and individual forms do not need to use the token verification function, you can add {__NOTOKEN__} to the form page, and the system will ignore the token verification of the current form. If there are multiple forms on the page, it is recommended to add identification and ensure that only one form requires token verification. The model class will automatically perform form token verification when creating the data object. If you do not use the create method to create the data object, you need to manually call the autoCheckToken method of the model to perform form token verification. If false is returned, it indicates a form token validation error. For example: $User = M("User"); // Instantiate User object // Manual token verification if (!$User->autoCheckToken($_POST)){// Token verification error

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/868237.htmlTechArticleExample tutorial of create method and automatic token verification in ThinkPHP, thinkphpcreate This article shows the create method in ThinkPHP in the form of an example How to implement automatic token verification, the specific steps are as follows...
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to verify signature in PDF How to verify signature in PDF Feb 18, 2024 pm 05:33 PM

We usually receive PDF files from the government or other agencies, some with digital signatures. After verifying the signature, we see the SignatureValid message and a green check mark. If the signature is not verified, the validity is unknown. Verifying signatures is important, let’s see how to do it in PDF. How to Verify Signatures in PDF Verifying signatures in PDF format makes it more trustworthy and the document more likely to be accepted. You can verify signatures in PDF documents in the following ways. Open the PDF in Adobe Reader Right-click the signature and select Show Signature Properties Click the Show Signer Certificate button Add the signature to the Trusted Certificates list from the Trust tab Click Verify Signature to complete the verification Let

Detailed method to unblock using WeChat friend-assisted verification Detailed method to unblock using WeChat friend-assisted verification Mar 25, 2024 pm 01:26 PM

1. After opening WeChat, click the search icon, enter WeChat team, and click the service below to enter. 2. After entering, click the self-service tool option in the lower left corner. 3. After clicking, in the options above, click the option of unblocking/appealing for auxiliary verification.

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

New features in PHP 8: Added verification and signing New features in PHP 8: Added verification and signing Mar 27, 2024 am 08:21 AM

PHP8 is the latest version of PHP, bringing more convenience and functionality to programmers. This version has a special focus on security and performance, and one of the noteworthy new features is the addition of verification and signing capabilities. In this article, we'll take a closer look at these new features and their uses. Verification and signing are very important security concepts in computer science. They are often used to ensure that the data transmitted is complete and authentic. Verification and signatures become even more important when dealing with online transactions and sensitive information because if someone is able to tamper with the data, it could potentially

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

See all articles