gueff/phimcap

phimcap 提供了可以在自己的 HTML 表单中使用的验证码图片。

1.0.0 2023-05-07 16:13 UTC

This package is auto-updated.

Last update: 2024-09-07 19:21:36 UTC


README

这个类提供了你可以在自己的 HTML 表单中使用的验证码图片。

要求

  • Linux
  • php >=7.4
    • GD 库扩展
  • 存在类似于 FreeMono.ttf 的真类型字体

安装

{
  "require": {
    "gueff/phimcap":"1.0.*"
  }
}

如何使用

... 例如使用 myMVC 3.2.xforgotPassword

假设你的主要工作模块被命名为 Foo

1) 处理 HTML 表单

创建一个 MIX /forgotPassword/ 路由,指向 \Foo\Controller\Index::forgotPassword

\MVC\Route::MIX(
    ['GET', 'POST'],
    '/forgotPassword/',
    '\Foo\Controller\Index::forgotPassword',
    $oDTRoutingAdditional
        ->set_sLayout($sTheme . '/Frontend/layout/index.tpl')
        ->set_sContent($sTheme . '/Frontend/content/forgotPassword.tpl')
        ->getPropertyJson()
);

\Foo\Controller\Index::forgotPassword:创建新的验证码文本并将其保存到 Session 中

public function forgotPassword()
{
    // grab for POSTed captcha; sanitize
    $sCaptcha = substr(
        preg_replace("/[^\\p{L}\\p{N}']+/u", '', get($_POST['captcha'])),
        0,
        strlen(Session::is()->get('mymvc.captcha'))
    );

    if (
        ($sCaptcha === Session::is()->get('mymvc.captcha'))
    )
    {
        // stuff...
    }

    // create new captcha text & save to session
    $sCaptchaText = \Phimcap::text();
    Session::is()->set('mymvc.captcha', $sCaptchaText);

    $sContent = $this->oView->loadTemplateAsString('/Frontend/content/forgotPassword.tpl');
    $this->oView->assign('sContent', $sContent);
}

模板 /Frontend/content/forgotPassword.tpl

<form action="" method="post">
    <label for="captcha">Captcha</label>
    <img src="/captcha/">
    <input type="text"
           name="captcha"
           id="captcha" 
           class="form-control"
           value=""
           maxlength="5"
           placeholder="captcha code"
    >
</form>

2) 服务器端的验证码图片

创建 \Foo\Controller\Index::captcha

public function captcha()
{
    \Phimcap::image(
        Session::is()->get('mymvc.captcha')
    );
}
  • 这里从 Session 中获取验证码文本

创建一个 /captcha/ 路由,指向 \Foo\Controller\Index::captcha

\MVC\Route::GET(
    '/captcha/',
    '\Foo\Controller\Index::captcha'
);

因此,验证码图片可以通过以下方式调用

<img src="/captcha/">

自定义

使用不同的字体

Phimcap 使用 /usr/share/fonts/truetype/freefont/FreeMono.ttf,这可能是 Ubuntu Linux 系统默认安装的。

如果你想要不同的字体,请将绝对路径作为第二个参数添加

\Phimcap::image(
    Session::is()->get('mymvc.captcha'),
    '/usr/share/fonts/truetype/msttcorefonts/andalemo.ttf'
);

文本长度

默认情况下,文本长度设置为 5

你可以通过添加一个值将其更改为介于 510 之间的值。

$sCaptchaText = \Phimcap::text(10);