示例#1
0
 /**
  * 输出验证码并把验证码的值保存的session中
  * 验证码保存到session的格式为: $_SESSION[self::$seKey] = array('code' => '验证码值', 'time' => '验证码创建时间');
  */
 public static function entry($id = '')
 {
     // 图片宽(px)
     self::$imageL || (self::$imageL = self::$length * self::$fontSize * 1.5 + self::$fontSize * 1.5);
     // 图片高(px)
     self::$imageH || (self::$imageH = self::$fontSize * 2);
     // 建立一幅 self::$imageL x self::$imageH 的图像
     self::$_image = imagecreate(self::$imageL, self::$imageH);
     // 设置背景
     imagecolorallocate(self::$_image, self::$bg[0], self::$bg[1], self::$bg[2]);
     // 验证码字体随机颜色
     self::$_color = imagecolorallocate(self::$_image, mt_rand(1, 120), mt_rand(1, 120), mt_rand(1, 120));
     // 验证码使用随机字体
     $ttfPath = dirname(__FILE__) . '/captcha/' . (self::$useZh ? 'zhttfs' : 'ttfs') . '/';
     $dir = dir($ttfPath);
     $ttfs = array();
     while (false !== ($file = $dir->read())) {
         if ($file[0] != '.' && substr($file, -4) == '.ttf') {
             $ttfs[] = $ttfPath . $file;
         }
     }
     $dir->close();
     // print_r($ttfs);
     // exit;
     $ttf = $ttfs[array_rand($ttfs)];
     if (self::$useImgBg) {
         self::_background();
     }
     if (self::$useNoise) {
         // 绘杂点
         self::_writeNoise();
     }
     if (self::$useCurve) {
         // 绘干扰线
         self::_writeCurve();
     }
     // 绘验证码
     $code = array();
     // 验证码
     $codeNX = 0;
     // 验证码第N个字符的左边距
     for ($i = 0; $i < self::$length; $i++) {
         if (self::$useZh) {
             $code[$i] = chr(mt_rand(0xb0, 0xf7)) . chr(mt_rand(0xa1, 0xfe));
         } else {
             $code[$i] = self::$_codeSet[mt_rand(0, 8)];
             $codeNX += mt_rand(self::$fontSize * 1.2, self::$fontSize * 1.6);
             // 写一个验证码字符
             self::$useZh || imagettftext(self::$_image, self::$fontSize, mt_rand(-40, 40), $codeNX, self::$fontSize * 1.5, self::$_color, $ttf, $code[$i]);
         }
     }
     // 保存验证码
     isset($_SESSION) || session_start();
     if ($id) {
         $_SESSION[self::$seKey][$id]['code'] = join('', $code);
         // 把校验码保存到session
         $_SESSION[self::$seKey][$id]['time'] = time();
         // 验证码创建时间
     } else {
         $_SESSION[self::$seKey]['code'] = join('', $code);
         // 把校验码保存到session
         $_SESSION[self::$seKey]['time'] = time();
         // 验证码创建时间
     }
     self::$useZh && imagettftext(self::$_image, self::$fontSize, 0, (self::$imageL - self::$fontSize * self::$length * 1.2) / 3, self::$fontSize * 1.5, self::$_color, $ttf, iconv("GB2312", "UTF-8", join('', $code)));
     header('Cache-Control: private, max-age=0, no-store, no-cache, must-revalidate');
     header('Cache-Control: post-check=0, pre-check=0', false);
     header('Pragma: no-cache');
     header("content-type: image/png");
     // 输出图像
     imagepng(self::$_image);
     imagedestroy(self::$_image);
 }