php原生自定义验证码,5分钟搞定你的问题

当然现在很多php的框架里面自带了很多很多验证码,我的这个验证码,也是当初刚刚入行的时候学习模仿的。现在照搬出来,希望对刚入门的朋友有所帮助。

************************************************************************************************************

<?php
class CaptchaLib extends Base{
private $length; //验证码长度
private $font; //设置字体1-5
public function __construct($length=4,$font=5){
    $this->length = $length;
    $this->font = $font;
}
/**
* @intro    生成随机字符串
* 
* @param    
* 
* @author  十月桂花香十里
* 
* @return    
*/
private function generalCode(){
    $char_array = array_merge(range('A','Z'),range(0,9));
    $index = array_rand($char_array,$this->length);
    shuffle($index);
    //拼接验证码字符串
    $str = '';
    foreach($index as $i){
        $str .= $char_array[$i];
    }
    //将生成的随机字符串保存到会话中 
    session_start();
    $_SESSION['code'] = $str; 
    return $str;
}
/**
* @intro     生成验证码
* 
* @param    
* 
* @author  十月桂花香十里
* 
* @return    
*/
public function generalCaptcha(){
    $str = $this->generalCode();
    //打开图片路径
    $bg ='http://www.xxx.com/images/captcha/captcha_bg'.rand(1,5).'.jpg'; //这里引用你图片的存放的位置,记得注意不要被盗链了
  $img = imagecreatefromjpeg($bg);
  //定义字符串颜色,黑白概率为50%
  $color = imagecolorallocate($img,0,0,0);
  if(rand(1,2)==2){
      $color=imagecolorallocate($img,255,255,255);
  }
  $x=(imagesx($img)-imagefontwidth($this->font)*strlen($str))/2;
  $y=(imagesy($img)-imagefontheight($this->font))/2;
  imagestring($img,$this->font,$x,$y,$str,$color);
  //浏览器输出
  header('content-type:image/png');
  imagepng($img);
  imagedestroy($img);
}
/**
* @intro 验证输入的验证码是否正确
* 
* @param    $code string 用户输入的验证码    
* 
* @author  十月桂花香十里
* 
* @return bool 成功返回true,失败返回false    
*/
public function checkCode($code){
    return strtolower($code) == strtolower($_SESSION['code'])?true:false;
}
}

 

*******************************************************************

封装好的,直接复制就行,改一下背景图片地址就ok了,至于背景图片,我云盘分享一下就行。

(链接:http://pan.baidu.com/s/1i47wWKl 密码:sfvg)

posted @ 2016-10-10 15:54  十月桂花香十里  阅读(1199)  评论(0编辑  收藏  举报
我一辈子走过许多地方的路, 行过许多地方的桥, 看过许多次数的云, 喝过许多种类的酒, 如今却只爱一个正当最好年纪的人。