Blogger Information
Blog 65
fans 1
comment 1
visits 119011
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
tp5 使用自带token令牌验证
技术宅的博客
Original
2743 people have browsed it

首先参考手册的写法

写在html 表单的 推荐下面一种简单快捷
<input type="hidden" name="__token__" value="{$Request.token}" />
{:token()}

1.正常的表单提交

   protected $rule = [
        'name'  =>  'require|max:25|token',
        'email' =>  'email',
    ];
    怎么使用验证?
    这个token 随便你放在哪个表单字段 后面验证就好了 推荐就放第一个
    不用自己写一个
    '__token__'=>'token'
    所以就是在平时的验证上加一个token在第一个字段验证的后面即可 不可以多加 不然报错 验证不过

下面看一下demo

php 代码

public function index()
{
   if(Request::isGet()){
  return $this->fetch();
 }
 $data=input();
 $validate = Validate::make([
  'name|用户名'  => 'require|max:25|token',
  'password|密码' => 'require|max:16',
 ]);
 if (!$validate->check($data)) {
  return json(['status'=>1,'info'=>$validate->getError()]);
 }
 return json(['status'=>1,'info'=>'ok']);

}

html  表单版本

<form action="" method="post">
    <lable>姓名:</lable><input type="text" name="name" id="name" required="required" placeholder="请输入姓名"><br>
    <lable>密码:</lable><input type="text" name="password" id="password" required="required" placeholder="请输入密码"><br>
    {:token()}
    <button type="submit">提交</button>
</form>

html ajax版本

<div class="center">
    <form action="" id="form">
        <lable>姓名:</lable><input type="text" name="name" id="name" required="required" placeholder="请输入姓名"><br>
        <lable>密码:</lable><input type="text" name="password" id="password" required="required" placeholder="请输入密码"><br>
        {:token()}
        <button type="button" class="submit">提交</button>
    </form>
</div>
</body>
</html>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
    $(".submit").on('click',function(){
        $.ajax({
            type:'post',
            url: '{:url("Index/index")}',
            // data:$('#form').serialize(), 提交所有字段 表单的
            data: {'name':$('#name').val(),'password':$('#password').val(),'__token__':$("input[name='__token__']").val() },
            // 需要几个字段 需要自己传递一下 token 的值  
            dataType:'json',
            success: function(data) {
                if (data.status == 1) {
                    alert(data.info);
                } else {
                    alert(data.info);
                }
            }
        });
    });


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post