返回首页 - Notes - 2015

在 Symfony2 中生成验证码


  1. 编辑 composer.json,在 require 段中加入一行依赖:"gregwar/captcha": "1.*"
  2. 执行 composer update 安装依赖包
  3. 然后就可以在控制器里调用该依赖包啦,下面是具体的代码:
    <?php
    
    namespace Site\CommonBundle\Controller;
    
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
    use Symfony\Component\HttpFoundation\Response;
    use Gregwar\Captcha\PhraseBuilder;
    use Gregwar\Captcha\CaptchaBuilder;
    
    class DefaultController extends BaseController
    {
        /**
         * 生成验证码.
         *
         * @Route("captcha", name="site_common_captcha")
         */
        public function captchaAction()
        {
            $req = $this->getRequest();
    
            $width = intval($req->get('width')) ?: 150;  // 验证码图片的宽度
            $height = intval($req->get('height')) ?: 50;  // 验证码图片的高度
            $length = 5;  // 验证码字符的长度
            $no_effect = true;  // 是否忽略验证图片上的干扰线条
    
            $pharse = new PhraseBuilder();
            $captcha = new CaptchaBuilder($pharse->build($length));
            $image = $captcha->setIgnoreAllEffects($no_effect)->build($width, $height)->get();
    
            $session = $req->getSession();
            $session->set('captcha', $captcha->getPhrase());
    
            $res = new Response($image);
            $res->headers->set('content-type', 'image/jpeg');
    
            return $res;
        }
    }
    
  4. 如此,验证码图片的访问地址为:http://www.example.com/captcha?width=100&height=30(可以传递参数改变图片的尺寸)

date:2015-06-25