龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

php实现的验证码

时间:2014-06-27 02:17来源:网络整理 作者:网络 点击:
分享到:
php实现的验证码 新方式其实也不难懂,就是从 10 个字符中找出 4 个颜色不同的数字字符,而在工行的案例里面还包括了一个中文的文字描述,可能这样用户能更清楚该

新方式其实也不难懂,就是从 10 个字符中找出 4 个颜色不同的数字字符,而在工行的案例里面还包括了一个中文的文字描述,可能这样用户能更清楚该怎样做吧。

php验证码

下面是源码:

/**
 * 随机数函数
 * @param int $len 长度
 * @param mixed $type 类型
 * @return string
 */
function randomString($len, $type = null)
{
  $randstring = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  if (isset($type)) {
    if ($type == 10 || $type == 16) {
      $randstring = substr($randstring, 0, $type);
    } else if ($type == 'a') {
      $randstring = substr($randstring, 10);
    }
  }
  $length = strlen($randstring) - 1;
  $result = '';
  for ($i = 0; $i < $len; ++ $i) {
    $result .= $randstring[mt_rand(0, $length)];
  }
  return $result;
}
$im = imagecreatetruecolor(300, 50);
// 随机背景色
$bg = imagecolorallocate($im, mt_rand(0xcc, 0xff), mt_rand(0xcc, 0xff), mt_rand(0xcc, 0xff));
imagefill($im, 0, 0, $bg);
// 随机字符颜色
$fg = imagecolorallocate($im, mt_rand(0x00, 0x33), mt_rand(0x00, 0x33), mt_rand(0x00, 0x33));
// 随机高亮数字颜色
switch (mt_rand(1, 3)) {
  case 1:
    $hl = imagecolorallocate($im, mt_rand(0xcc, 0xff), mt_rand(0x33, 0x99), mt_rand(0x33, 0x99));
    break;
  case 2:
    $hl = imagecolorallocate($im, mt_rand(0x33, 0x66), mt_rand(0x99, 0xcc), mt_rand(0x33, 0x99));
    break;
  case 3:
    $hl = imagecolorallocate($im, mt_rand(0x33, 0x99), mt_rand(0x33, 0x99), mt_rand(0xcc, 0xff));
    break;
}
$fontfile = './alloveragain.ttf';
// 获取高亮数字验证码
$captchaValue = randomString(4, 10);
$textLen = 10;
// 获取随机字符串
$text = randomString($textLen, 'a');
// 随机获取高亮数字位置并替换
$hltext = array_rand(str_split($text), 4);
foreach ($hltext as $key => $idx) {
  $text[$idx] = $captchaValue[$key];
}
// 随机位置、大小、角度显示字符串
for ($i = 0; $i < $textLen; ++$i) {
  imagettftext($im, mt_rand(15, 25), mt_rand(0, 30) - 15, 28 * $i + mt_rand(10, 20),
    mt_rand(35, 45), in_array($i, $hltext) ? $hl : $fg, $fontfile, $text[$i]);
}
header('Expires: Mon, 26 Jul 1970 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

需要的朋友可以在此下载

精彩图集

赞助商链接