看文档很简单的一个功能,只要注意点版本对应,别下载错了就可,结果踩坑了……
1、验证码功能不是系统内置的功能,需要通过composer引入进来;
win+r输入cmd,进入项目根目录,输入:
composer require topthink/think-captcha=2.0.*
composer require topthink/think-captcha=1.*
注意
tp5.0用1.*
tp5.1用2.0
2、引用显示验证码
//下面两个任选一个
<div>{:captcha_img()}</div>
<div><img src="{:captcha_src()}" alt="captcha" /></div>
//网页点击刷新验证码
<img src="{:captcha_src()}" onclick="this.src='{:captcha_src()}?'+Math.random();" style="height: 36px"/>
或者修改源码实现点击刷新,修改打开 ..\vendor\topthink\think-captcha\src\helper.php 文件,替换 captcha_img() 方法代码.
function captcha_img($id = "")
{
$js_src = "this.src='".captcha_src()."'";
return '<img src="' . captcha_src($id) . '" title="点击更新验证码" alt="点击更新验证码" οnclick="'.$js_src.'" />';
//return '![](' . captcha_src($id) . ')';
}
3、后台获取验证
最简单的方法
if(request()->isPost()){
$data = input('post.');
if(!captcha_check($data['verifyCode'])) {
// 校验失败
$this->error('验证码不正确');
}
}
4、然后踩坑经历:一直报错,致命错误: Call to undefined function captcha_img()
原因是,composer 安装的扩展autoload文件里面竟然没有自动生成方法目录,导致获取不到helper中的全局方法……解决如下:
①、打开vendor/composer/autoload_psr4.php
加入 ‘think\captcha\’ => array($vendorDir . ‘/topthink/think-captcha/src’),
return array(
'think\\composer\\' => array($vendorDir . '/topthink/think-installer/src'),
'think\\captcha\\' => array($vendorDir . '/topthink/think-captcha/src'),
'app\\' => array($baseDir . '/application'),
);
②、composer下添加autoload_files.php
<?php
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'1cfd2761b63b0a29ed23657ea394cb2d' => $vendorDir . '/topthink/think-captcha/src/helper.php',
);
③、编辑autoload_static.php
添加以下代码
public static $files = array (
'1cfd2761b63b0a29ed23657ea394cb2d' => __DIR__ . '/..' . '/topthink/think-captcha/src/helper.php',
);
...
array (
'think\\composer\\' => 15,
'think\\captcha\\' => 14,
),
...
'think\\composer\\' =>
array (
0 => __DIR__ . '/..' . '/topthink/think-installer/src',
),
'think\\captcha\\' =>
array (
0 => __DIR__ . '/..' . '/topthink/think-captcha/src',
),
④、编辑autoload_real.php
查看自己autoload_static.php类名,并添加添加函数composerRequirec6c13346c3bda597899f762f41f5ad54调用
public static function getLoader()
{
...
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\自己的autoload_static.php的类名::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequirec6c13346c3bda597899f762f41f5ad54($fileIdentifier, $file);
}
return $loader;
}
//添加函数
function composerRequirec6c13346c3bda597899f762f41f5ad54($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}
⑤、好了,可以正常调用了(解决方法原文引用自:https://blog.csdn.net/ruancexiaoming/article/details/89606563)