php验证码类

系统 1818 0

1. php验证码类 点击可刷新

 

1、验证码类文件 CreateImg.class.php

      <?php

class ValidationCode
{
private $width,$height,$codenum;
public $checkcode;     //产生的验证码
private $checkimage;    //验证码图片
private $disturbColor = ''; //干扰像素

function __construct($width='80',$height='20',$codenum='4')
{
   $this->width=$width;
   $this->height=$height;
   $this->codenum=$codenum;
}
function outImg()
{
   //输出头
   $this->outFileHeader();
   //产生验证码
   $this->createCode();

   //产生图片
   $this->createImage();
   //设置干扰像素
   $this->setDisturbColor();
   //往图片上写验证码
   $this->writeCheckCodeToImage();
   imagepng($this->checkimage);
   imagedestroy($this->checkimage);
}

private function outFileHeader()
{
   header ("Content-type: image/png");
}

private function createCode()
{
   $this->checkcode = strtoupper(substr(md5(rand()),0,$this->codenum));
}

private function createImage()
{
   $this->checkimage = @imagecreate($this->width,$this->height);
   $back = imagecolorallocate($this->checkimage,255,255,255);
   $border = imagecolorallocate($this->checkimage,0,0,0);  
   imagefilledrectangle($this->checkimage,0,0,$this->width - 1,$this->height - 1,$back); // 白色底
   imagerectangle($this->checkimage,0,0,$this->width - 1,$this->height - 1,$border);   // 黑色边框
}

private function setDisturbColor()
{
   for ($i=0;$i<=200;$i++)
   {
    $this->disturbColor = imagecolorallocate($this->checkimage, rand(0,255), rand(0,255), rand(0,255));
    imagesetpixel($this->checkimage,rand(2,128),rand(2,38),$this->disturbColor);
   }
}

private function writeCheckCodeToImage()
{
   for ($i=0;$i<=$this->codenum;$i++)
   {
    $bg_color = imagecolorallocate ($this->checkimage, rand(0,255), rand(0,128), rand(0,255));
    $x = floor($this->width/$this->codenum)*$i;
    $y = rand(0,$this->height-15);
    imagechar ($this->checkimage, rand(5,8), $x, $y, $this->checkcode[$i], $bg_color);
   }
}
function __destruct()
{
   unset($this->width,$this->height,$this->codenum);
}
}
?>
    

 

2、包含文件 imgcode.php

      <?php
session_start();
require_once('CreateImg.class.php');
$image = new ValidationCode('80','20','4');    //图片长度、宽度、字符个数
$image->outImg();
$_SESSION['validationcode'] = $image->checkcode; //存贮验证码到 $_SESSION 中
?>
    

 

3、前台文件 demo.php

      ?php
session_start();
$test = $_POST['test'];
$test = strtoupper(trim($test));
$submit = $_POST['submit'];
if(isset($submit)){
if($test==$_SESSION['validationcode']){
   echo 'true';
} else {
   echo 'false';
}
}
?>

<html>
<head>
<title>Image</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script language="javascript">
function newgdcode(obj,url) {
obj.src = url+ '?nowtime=' + new Date().getTime();
//后面传递一个随机参数,否则在IE7和火狐下,不刷新图片
}
</script>
<body>
<img src="imgcode.php" alt="看不清楚,换一张" align="absmiddle" style="cursor: pointer;" onclick="javascript:newgdcode(this,this.src);" />
<form method="POST" name="form1" action="image.php">
<input type="text" name="test">
<br />
<input type="submit" name="submit" value="提交">
</form>
</body>
</head>
</html>
    

 

2. jQuery插件Real Person 点击可刷新

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.realperson.js"></script>
<link href="jquery.realperson.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
	$(function(){
		$('#Gideon').realperson({length: 5});
	})
</script>
</head>

<body>

<input type="text" id="Gideon" name="defaultReal">
</body>
</html>
    

 

来源: http://keith-wood.name/realPerson.html

 

注:如果持续无法验证成功的话,请尝试下面的方法:

      <?php
function rpHash($value) {
	$hash = 5381;
	$value = strtoupper($value);
	for($i = 0; $i < strlen($value); $i++) {
		$hash = (($hash << 5) + $hash) + ord(substr($value, $i));
	}
	return $hash;
}
?>
    

 

替换为:

      <?
	function rpHash($value) 
	{
	    $hash = 5381;
	    $value = strtoupper($value);
	    for($i = 0; $i < strlen($value); $i++)  $hash = (leftShift32($hash, 5) + $hash) + ord(substr($value, $i));
	    return $hash; 
	}

	function leftShift32($number, $steps) 
	{
	    $binary = decbin($number);
	    $binary = str_pad($binary, 32, "0", STR_PAD_LEFT);
	    $binary = $binary.str_repeat("0", $steps);
	    $binary = substr($binary, strlen($binary) - 32);
	    return ($binary{0} == "0" ? bindec($binary) : -(pow(2, 31) - bindec(substr($binary, 1)))); 
	}
?>
    

 

3. php验证码 可计算(有限)

demo.php

      <?php
session_start();
if(!empty($_POST['Login'])){
	if(md5(strtoupper($_POST['Login'])) == $_SESSION['Login']){
		echo 'Correct';
	}else{
		echo 'Error';	
	}
}
?>

<form method="post">
    <input type="text" name="Login" value="" /><img src="img.php?Action=Login&imgW=80&imgH=30" align="absmiddle">
    <input type="submit" value="Login" />
</form>
    

 

img.php

      <?php
session_start();
  /**
* 随机的数字,之和验证码
* 修改日期 2006-12-20
*/
function getCode ($length = 32, $mode = 0)
{
switch ($mode)
{
     case '1':
         $str = '123456789';
            break;
  case '2':
            $str = 'abcdefghijklmnopqrstuvwxyz';
            break;
  case '3':
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
  case '4':
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
            break;
  case '5':
            $str = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789';
            break;
        case '6':
            $str = 'abcdefghijklmnopqrstuvwxyz1234567890';
            break;
        default:
            $str = 'ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
            break;
}

$result = '';
$l = strlen($str)-1;
for($i = 0;$i < $length;$i ++)
{
  $num = rand(0, $l);
  $result .= $str[$num];
}
return $result;
}
//建立验证图片
function createAuthNumImg($randStr,$imgW=100,$imgH=40,$fontName)
{
header ("content-type: image/png");
$image = imagecreate($imgW , $imgH);
$color_white = imagecolorallocate($image , 255 , 255 , 255);
$color_gray  = imagecolorallocate($image , 228 , 228 , 228);
$color_black = imagecolorallocate($image , 255 , 102 , 204);
for ($i = 0 ; $i < 1000 ; $i++)
{
  imagesetpixel($image , mt_rand(0 , $imgW) , mt_rand(0 , $imgH) , $color_gray);
}
imagerectangle($image , 0 , 0 , $imgW - 1 , $imgH - 1 , $color_gray);
for ($i=10;$i<$imgH;$i+=10)
  imageline($image, 0, $i, $imgW, $i, $color_gray);
imagettftext($image,16,5,3,25,$color_black,$fontName,$randStr);
for ($i=10;$i<$imgW;$i+=10)
  imageline($image, $i, 0, $i, $imgH, $color_gray);
imagepng($image);
imagedestroy($image);
}

$a=GetCode(1,1);
$b=GetCode(1,1);
$c=GetCode(1,1);
$Passport=$a."+".$b."+".$c;
$Total=$a+$b+$c;
$Total;
$_SESSION[$_GET['Action']]=md5(strtoupper($Total));
createAuthNumImg($Passport,$_GET['imgW'],$_GET['imgH'],"verdana.ttf");
?>
    

 

3. Recaptcha(需要申请key,不过是免费的,类似Google key)

官网: http://recaptcha.net/resources.html

 

php验证码类

 

Examples

The following is a "Hello World" with reCAPTCHA:

      <html>
  <body>
    <form action="" method="post">
<?php

require_once('recaptchalib.php');

// Get a key from http://recaptcha.net/api/getkey
$publickey = "6Lfc4wsAAAAAAM2-W6LHIYIA0NphCqZniVIXAKmp";
$privatekey = "6Lfc4wsAAAAAAEat7eqgrzOim3HG_lrzQ9_fvzwU";

# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;

# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
        $resp = recaptcha_check_answer ($privatekey,
                                        $_SERVER["REMOTE_ADDR"],
                                        $_POST["recaptcha_challenge_field"],
                                        $_POST["recaptcha_response_field"]);

        if ($resp->is_valid) {
                echo "You got it!";
        } else {
                # set the error code so that we can display it
                $error = $resp->error;
        }
}
echo recaptcha_get_html($publickey, $error);
?>
    <br/>
    <input type="submit" value="submit" />
    </form>
  </body>
</html>
    

 

The following example shows how to use Mailhide:

 

      <html><body>
<?
require_once ("recaptchalib.php");
// get a key at http://mailhide.recaptcha.net/apikey
$mailhide_pubkey = '';
$mailhide_privkey = '';
?>
The Mailhide version of example@example.com is
<?
echo recaptcha_mailhide_html ($mailhide_pubkey,
                              $mailhide_privkey,
                              "example@example.com");
?>.
<br>
The url for the email is:
<?
echo recaptcha_mailhide_url ($mailhide_pubkey,
                             $mailhide_privkey,
                             "example@example.com");
?>
<br>
</body></html>

    

 

If you're looking for some more examples, take a look at the WordPress and MediaWiki plugins, which use this library.

 

4. 其他

带声音。

php验证码类


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论