|
总结:本篇博客介绍使用gregwar/captcha实现验证码的具体操作步骤,以及可能遇到的问题和解决办法。 操作步骤: 1, 在laravel5.4项目根目录下找到 composer.json 这个文件, 添加 "gregwar/captcha": "1.*" 到composer.json这个文件中,如下图所示。 2. 然后打开命令行,找到项目的根目录,运行composer update, 可以看到这个扩展库已经下载好了, 3.接下来,就可以正常使用验证码了,先测试验证码是否可以正常显示出来, 先定义路由: 然后在控制层里新建一个codeController.php,
<?php
namespace AppHttpControllers;
use AppHttpRequests;
use AppHttpControllersController;
use IlluminateHttpRequest;
//引用对应的命名空间
use GregwarCaptchaCaptchaBuilder;
use Session;
class CodeController extends Controller{
public function captcha($temp)
{
$builder = new CaptchaBuilder();
$builder->build(150,32);
$phrase = $builder->getPhrase();
//把内容存入session
Session::flash('milkcaptcha', $phrase); //存储验证码
ob_clean();
return response($builder->output())->header('Content-type','image/jpeg');
}
} 另外,还可以在composer.json中这样写, 还是在项目根目录执行composer update,然后在执行composer dump-autoload 命令。 同样可以达到效果。 最后,说一下我曾经遇到的问题,网上好多生成laravel验证码图片都是这样写的,
public function code($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();
}我照着试了试,结果验证码图片显示乱码,不显示图片,如下图: 后来改了改,这样写之后 public function captcha($temp)
{
$builder = new CaptchaBuilder();
$builder->build(150,32);
$phrase = $builder->getPhrase();
//把内容存入session
Session::flash('milkcaptcha', $phrase); //存储验证码
ob_clean();
return response($builder->output())->header('Content-type','image/jpeg');
}就可以正常显示了。 本文转载于: |