laravel框架中表单请求类型和CSRF防护实例分析

吾爱主题 阅读:114 2021-09-17 12:22:00 评论:0

本文实例讲述了laravel框架中表单请求类型和CSRF防护。分享给大家供大家参考,具体如下:

laravel中为我们提供了绑定不同http请求类型的函数。

?
1 2 3 4 5 6 Route::get( '/test' , function () {}); Route::post( '/test' , function () {}); Route::put( '/test' , function () {}); Route::patch( '/test' , function () {}); Route:: delete ( '/test' , function () {}); Route::options( '/test' , function () {});

但有些时候,我们通过创建资源控制器,里面的 update() 方法绑定的是 PUT 类型的http请求。

这就需要我们通过表单提交模拟PUT请求。我们可以自已添加一个 _method 的隐藏字段,值为 PUT。

?
1 2 3 4 5 6 <form action= "{{ route('test') }}" method= "post" >    <input type= "hidden" name= "_method" value= "PUT" >    用户名:<input type= "text" name= "name" >    密码:<input type= "password" name= "pwd" >    <input type= "submit" value= "提交" > </form>

也可以使用laravel为我们提供的 method_field() 方法。

?
1 2 3 4 5 6 <form action= "{{ route('test') }}" method= "post" >    {{ method_field( 'PUT' ) }}    用户名:<input type= "text" name= "name" >    密码:<input type= "password" name= "pwd" >    <input type= "submit" value= "提交" > </form>

laravel默认会对每个提交请求,进行csrf令牌的验证。为了通过验证,需要在表单中添加 _token 隐藏字段。

?
1 2 3 4 5 6 <form action= "{{ route('test') }}" method= "post" >    <input type= "hidden" name= "_token" value= "{{ csrf_token() }}" >    用户名:<input type= "text" name= "name" >    密码:<input type= "password" name= "pwd" >    <input type= "submit" value= "提交" > </form>

或者使用 csrf_field() 方法。

?
1 2 3 4 5 6 <form action= "{{ route('test') }}" method= "post" >    {{ csrf_field() }}    用户名:<input type= "text" name= "name" >    密码:<input type= "password" name= "pwd" >    <input type= "submit" value= "提交" > </form>

希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。

原文链接:https://www.cnblogs.com/jkko123/p/10805728.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容