laravel 生成验证码的方法

来源:互联网 发布:人工智能的原理 编辑:程序博客网 时间:2024/05/17 01:44

在Laravel中有很多图片验证码的库可以使用,本篇介绍其中之一:gregwar/captcha,这个库比较简单,在Laravel中比较常用。下面我们就来介绍下使用细节:

首先, composer.json中如下加入配置:

"require": {        ...        "gregwar/captcha": "1.*"    },

然后,已成习惯的命令:用cmd执行下面这条命令

   composer update

以下演示了其中一种使用方式,直接输出图片到网页。

我定义了一个Controller:

<?php namespace App\Http\Controllers;use App\Http\Requests;use App\Http\Controllers\Controller;use Illuminate\Http\Request;//引用对应的命名空间use Gregwar\Captcha\CaptchaBuilder;use Session;class KitController extends Controller {    /**     * Display a listing of the resource.     *     * @return Response     */    public function captcha($tmp)    {                //生成验证码图片的Builder对象,配置相应属性        $builder = new CaptchaBuilder;        //可以设置图片宽高及字体        $builder->build($width = 100, $height = 40, $font = null);        //获取验证码的内容        $phrase = $builder->getPhrase();        //把内容存入session        Session::flash('milkcaptcha', $phrase);        //生成图片        header("Cache-Control: no-cache, must-revalidate");        header('Content-Type: image/jpeg');        $builder->output();    }}

下面我们可以设置相应的router访问这个验证码图片, 修改router.php:

Route::get('kit/captcha/{tmp}', 'KitController@captcha');

现在可以通过具体的url,可以访问看到这张图片了


验证码

表单内部写的比较简单,看看即可:

<form action="wer_add" method="get">      <table>       用户名: <input type="text" name="username"><br>       密码: <input type="text" name="password"><br>         11: <input type="text" name="captcha"  style="width: 100px; height:20px "></br>          <a onclick="javascript:re_captcha();" >            <img src="{{ URL('kit/captcha/1') }}"  alt="验证码" title="刷新图片" width="100" height="40" id="c2c98f0de5a04167a9e427d883690ff6" border="0">        </a><br>         <input type="submit" value="提交">          </table>  </form><script>    function re_captcha() {    $url = "{{ URL('kit/captcha') }}";        $url = $url + "/" + Math.random();        document.getElementById('c2c98f0de5a04167a9e427d883690ff6').src=$url;  }</script>

最后就是在form提交页面验证相应验证码,库中也为我们提供了相应方法:

public function wer_add(){       $username=Request::input("username");        $password=Request::input("password");        //读取验证码        $captcha = Session::get('milkcaptcha');        if(Request::input("captcha")==$captcha){            $results = DB::select('select * from v9_admin where username = ? and password = ? ',array($username,$password));                        if(empty($results)){                echo '用户名或密码错误';            }else{                $userid=$results[0]->userid;                Session::put('username',$username);                Session::put('userid',$userid);                            echo '登陆成功';            }        }else{            echo '验码错误';        }    }    

至此,验证码就完成了。 如有疑问,欢迎回复探讨。


转至:http://www.cnblogs.com/chen5421/p/5717561.html

0 0