首页 > 编程技术 > php

一个简单php验证码程序代码

发布时间:2016-11-25 15:23

网上生成php验证码程序用很多,下面我来给大家分享一款超不错的php验证码程序代码,有需要的朋友可参考。

验证码识别一般分为以下几个步骤:

1. 取出字模
2. 二值化
3. 计算特征
4. 对照样本

 代码如下 复制代码


function _code($_code_length = 4, $_width = 75, $_height = 25){
    for($i=0;$i<$_code_length;$i++){
        $_nmsg .= dechex(mt_rand(0,15));
    }
    $_SESSION["code"] = $_nmsg;

    $_img = imagecreatetruecolor($_width, $_height);

    $_white = imagecolorallocate($_img, 250, 250, 250);

    imagefill($_img, 0, 0, $_white);

    $_gray = imagecolorallocate($_img, 196, 196, 196);

    imagerectangle($_img, 0, 0, $_width-1, $_height-1, $_gray);

    for ($i=0; $i < 6; $i++) {
        $_md_color = imagecolorallocate($_img, mt_rand(200,255), mt_rand(200,255), mt_rand(200,255));
        imageline($_img, mt_rand(0,$_width), mt_rand(0, $_height),mt_rand(0,$_width), mt_rand(0, $_height), $_md_color);
    }

    for ($i=0; $i < 50; $i++) {
        $_md_color = imagecolorallocate($_img, mt_rand(200,255), mt_rand(200,255), mt_rand(200,255));
        imagestring($_img, 1, mt_rand(1,$_width-5), mt_rand(1, $_height-5), "*", $_md_color);
    }

    for ($i=0; $i < $_code_length ; $i++) {
        $_md_color = imagecolorallocate($_img, mt_rand(0,102), mt_rand(0,102), mt_rand(0,102));
        imagestring($_img, 5, $i * $_width/$_code_length+ mt_rand(1, 10), mt_rand(1, $_height/2), $_SESSION["code"][$i], $_md_color);
    }

    header("Content-Type:image/png");

    imagepng($_img);

    imagedestroy($_img);
}

验证码使用方法

 代码如下 复制代码

$getcode = $_POST['code'];

if( $_SESSION["code"] = $getcode )
{
  echo ' 验证合法,进入下一步';
  unset( $_SESSION["code"] );
}
else
{
  echo ' 验证码不正确';
  header('location:vial.php');
}

虽然国内很多PHP程序员仍在依靠addslashes防止SQL注入,还是建议大家加强中文防止SQL注入的检查。addslashes的问题在 于黑客 可以用0xbf27来代替单引号,而addslashes只是将0xbf27修改为0xbf5c27,成为一个有效的多字节字符,其中的0xbf5c仍会 被看作是单引号,所以addslashes无法成功拦截。

当然addslashes也不是毫无用处,它是用于单字节字符串的处理,多字节字符还是用mysql_real_escape_string吧。

打开magic_quotes_gpc来防止SQL注入

php.ini中有一个设置:magic_quotes_gpc = Off
  这个默认是关闭的,如果它打开后将自动把用户提交对sql的查询进行转换,
  比如把 ' 转为 '等,对于防止sql注射有重大作用。

     如果magic_quotes_gpc=Off,则使用addslashes()函数

另外对于php手册中get_magic_quotes_gpc的举例:

 代码如下 复制代码

if (!get_magic_quotes_gpc()) {

  $lastname = addslashes($_POST[‘lastname’]);

  } else {

  $lastname = $_POST[‘lastname’];

}

最好对magic_quotes_gpc已经开放的情况下,还是对$_POST[’lastname’]进行检查一下。

再说下mysql_real_escape_string和mysql_escape_string这2个函数的区别:

mysql_real_escape_string 必须在(PHP 4 >= 4.3.0, PHP 5)的情况下才能使用。否则只能用 mysql_escape_string ,两者的区别是:mysql_real_escape_string 考虑到连接的当前字符集,而mysql_escape_string 不考虑。

(1)mysql_real_escape_string -- 转义 SQL 语句中使用的字符串中的特殊字符,并考虑到连接的当前字符集

使用方法如下:

 代码如下 复制代码

$sql = "select count(*) as ctr from users where username02.='".mysql_real_escape_string($username)."' and 03.password='". mysql_real_escape_string($pw)."' limit 1";


自定函数

 代码如下 复制代码


function inject_check($sql_str) {
    return eregi('select|insert|and|or|update|delete|'|/*|*|../|./|union|into|load_file|outfile', $sql_str);
}
 
function verify_id($id=null) {
    if(!$id) {
        exit('没有提交参数!');
    } elseif(inject_check($id)) {
        exit('提交的参数非法!');
    } elseif(!is_numeric($id)) {
        exit('提交的参数非法!');
    }
    $id = intval($id);
    
    return $id;
}
 
 
function str_check( $str ) {
    if(!get_magic_quotes_gpc()) {
        $str = addslashes($str); // 进行过滤
    }
    $str = str_replace("_", "_", $str);
    $str = str_replace("%", "%", $str);
    
   return $str;
}
 
 
function post_check($post) {
    if(!get_magic_quotes_gpc()) {
        $post = addslashes($post);
    }
    $post = str_replace("_", "_", $post);
    $post = str_replace("%", "%", $post);
    $post = nl2br($post);
    $post = htmlspecialchars($post);
    
    return $post;
}

总结一下:

* addslashes() 是强行加;

* mysql_real_escape_string() 会判断字符集,但是对PHP版本有要求;
* mysql_escape_string不考虑连接的当前字符集。
dz中的防止sql注入就是用addslashes这个函数,同时在dthmlspecialchars这个函数中有进行一些替换$string = preg_replace(/&((#(d{3,5}|x[a-fA-F0-9]{4}));)/, &1,这个替换解决了注入的问题,同时也解决了中文乱码的一些问题。

在网站开发中为了提供用户体验我们多数都使用ajax来做一些操作,下面我来介绍一个利用ajax实现无刷新页面的验证码ajax验证有需要的朋友可参考。

验证码生成程序我这里就不介绍了,大家可参考http://www.111cn.net/phper/phpanqn/46698.htm 下面介绍一个简单的

 代码如下 复制代码

<?php 
session_start();
//设置: 你可以在这里修改验证码图片的参数
$image_width = 120;
$image_height = 40;
$characters_on_image = 6;
$font = './monofont.ttf'; 
 
//以下字符将用于验证码中的字符 
//为了避免混淆去掉了数字1和字母i
$possible_letters = '23456789bcdfghjkmnpqrstvwxyz';
$random_dots = 10;
$random_lines = 30;
$captcha_text_color="0x142864";
$captcha_noice_color = "0x142864"; 
 
$code = ''; 
 
$i = 0;
while ($i < $characters_on_image) { 
    $code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
    $i++;
}
 
$font_size = $image_height * 0.75; 
$image = @imagecreate($image_width, $image_height);
 
/* 设置背景、文本和干扰的噪点 */
$background_color = imagecolorallocate($image, 255, 255, 255);
 
$arr_text_color = hexrgb($captcha_text_color); 
$text_color = imagecolorallocate($image, $arr_text_color['red'], 
$arr_text_color['green'], $arr_text_color['blue']);
 
$arr_noice_color = hexrgb($captcha_noice_color); 
$image_noise_color = imagecolorallocate($image, $arr_noice_color['red'], 
$arr_noice_color['green'], $arr_noice_color['blue']);
 
/* 在背景上随机的生成干扰噪点 */
for( $i=0; $i<$random_dots; $i++ ) {
    imagefilledellipse($image, mt_rand(0,$image_width),
    mt_rand(0,$image_height), 2, 3, $image_noise_color);
}
 
/* 在背景图片上,随机生成线条 */
for( $i=0; $i<$random_lines; $i++ ) {
    imageline($image, mt_rand(0,$image_width), mt_rand(0,$image_height),
    mt_rand(0,$image_width), mt_rand(0,$image_height), $image_noise_color);
}
 
/* 生成一个文本框,然后在里面写生6个字符 */
$textbox = imagettfbbox($font_size, 0, $font, $code); 
$x = ($image_width - $textbox[4])/2;
$y = ($image_height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code);
 
/* 将验证码图片在HTML页面上显示出来 */
header('Content-Type: image/jpeg');
// 设定图片输出的类型
imagejpeg($image);
//显示图片
imagedestroy($image);
//销毁图片实例
$_SESSION['6_letters_code'] = $code;
 
function hexrgb ($hexstr) {
    $int = hexdec($hexstr);
 
    return array( "red" => 0xFF & ($int >> 0x10),
                "green" => 0xFF & ($int >> 0x8),
                "blue" => 0xFF & $int
    );
}
?>

验证码

生成后,我们要在实际的项目中应用,通常我们使用ajax可以实现点击验证码时刷新生成新的验证码(有时生成的验证码肉眼很难识别),即“看不清换一张”。填写验证码后,还需要验证所填验证码是否正确,验证的过程是要后台程序来完成,但是我们也可以通过ajax来实现无刷新验证。

验证验证码正确或错误的方法
验证码图片上的文字被存放到了SESSION 变量里面,验证的时候,我们需要将SESSION 里面的值和用户输入的值进行比较即可。

$_SESSION[6_letters_code] – 存放着验证码的文字值
$_POST[6_letters_code] – 这是用户输入的验证码的内容


我们建立一个前端页面index.html,载入jquery,同时在body中加入验证码表单元素:

 代码如下 复制代码

<p>验证码:<input type="text" class="input" id="code_num" name="code_num" maxlength="4" />  
<img src="code_num.php" id="getcode_num" title="看不清,点击换一张" align="absmiddle"></p> 
<p><input type="button" class="btn" id="chk_num" value="提交" /></p> 

html代码中,<img" width=100% src="code_num.php"即调用了生成的验证码,当点击验证码时,刷新生成新的验证码:

 代码如下 复制代码

$(function(){ 
    //数字验证 
    $("#getcode_num").click(function(){ 
        $(this).attr("src",'code_num.php?' + Math.random()); 
    }); 
    ... 
}); 

刷新验证码,其实就是重新请求了验证码生成程序,这里要注意的是调用code_num.php时要带上随机参数防止缓存。接下来填写好验证码之后,点“提交”按钮,通过$.post(),前端向后台chk_code.php发送ajax请求。

 代码如下 复制代码

$(function(){ 
    ... 
    $("#chk_num").click(function(){ 
        var code_num = $("#code_num").val(); 
        $.post("chk_code.php?act=num",{code:code_num},function(msg){ 
            if(msg==1){ 
                alert("验证码正确!"); 
            }else{ 
                alert("验证码错误!"); 
            } 
        }); 
    }); 
}); 


后台chk_code.php验证:

 代码如下 复制代码

session_start(); 
 
$code = trim($_POST['code']); 
if($code==$_SESSION["helloweba_num"]){ 
   echo '1'; 

后台根据提交的验证码与保存在session中的验证码比对,完成验证。

本文章给大家介绍利用session存储与gd库一并生成验证码程序,同时会加入一些干扰元素,这样就可以简单的防机器注册了,下面我来给各位同学介绍介绍。

PHP验证码并生成图片程序,采用了session识别,稍微改进了一下目前网络上流传的PHP验证码,加入杂点,数字颜色随机显示,控制4位数字显示;话不多说了,程序如下,分享出来。

新建yz.php验证码生成文件:

注意:以下代码需要打开php的GD库,修改php.in文件的配置,把已经注释掉的行之前的分号取消即可:extension=php_gd2.dll。

 代码如下 复制代码

<?php
   class ValidationCode
   {
    //属性
    private $width;
    private $height;
    private $codeNum;
       private  $image;
    private $disturbColorNum;  //干扰元素数目
    private  $checkCode;
    function __construct($width=80,$height=20,$codeNum=4)
     {
     $this->width=$width;
     $this->height=$height;
     $this->codeNum=$codeNum;
     $number=floor($width*$height/15);
     if($number>240-$codeNum)
    {
      $this->disturbColorNum=240-$codeNum;
     }else
      {
      $this->disturbColorNum=$number;
      }
      $this->checkCode=$this->createCheckcode();
    }
    function getCheckCode()
    {
           return $this->checkCode;
    }
    private function createImage(){
          $this->image=imagecreatetruecolor($this->width,$this->height);
    $backcolor=imagecolorallocate($this->image,rand(225,255),rand(225,255),rand(255,255));
    imagefill($this->image,0,0,$backcolor);
    $border=imagecolorallocate($this->image,0,0,0);
    imagerectangle($this->image,0,0,$this->width-1,$this->height-1,$border);
    }
    private function setDisturbColor(){
     for($i=0;$i<$this->disturbColorNum;$i++){
      $color=imagecolorallocate($this->image,rand(0,255),rand(0,255),rand(0,255));
     imagesetpixel($this->image,rand(1,$this->width-2),rand(1,$this->height-2),$color);
     }
     for($i=0;$i<10;$i++)
     {
                  $color=imagecolorallocate($this->image,rand(0,255),rand(0,255),rand(0,255));
      imagearc($this->image,rand(-10,$this->width),rand(-10,$this->height),rand(30,300),rand(20,300),55,44,$color);
     }
    }
      private function outputText($fontFace=""){
    for($i=0;$i<$this->codeNum;$i++)
    {
     $fontcolor=imagecolorallocate($this->image,rand(0,128),rand(0,128),rand(0,128));
    if($fontFace=="")
   {
     $fontsize=rand(3,5);
     $x=floor($this->width/$this->codeNum)*$i+5;
     $y=rand(0,$this->height-15);
     imagechar($this->image,$fontsize,$x,$y,$this->checkCode{$i},$fontcolor);
    }
    else
   {
     $fontsize=rand(12,16);
     $x=floor(($this->width-8)/$this->codeNum)*$i+8;
     $y=rand($fontsize,$this->height-8);
     imagettftext($this->image,$fontsize,rand(-45,45),$x,$y,$fontcolor,$fontFace,$this->checkCode{$i});
    }
    }
   }

   private function createCheckCode(){
    $code="23456789abcdefghijkmnpqrstuvwrst";
    $str="";
    for($i=0;$i<$this->codeNum;$i++)
    {
     $char=$code{rand(0,strlen($code)-1)};
     $str.=$char;
    }
    return $str;
   }
   private function outputImage()
    {
    if(imagetypes()&IMG_GIF)
     {
       header("Content-Type:image/gif");
        imagepng($this->image);
     }else if(imagetypes()&IMG_JPG)
     {
        header("Content-Type:image/jpeg");
        imagepng($this->image);
     }else if(imagetypes()&IMG_PNG)
     {
        header("Content-Type:image/png");
      imagepng($this->image);
     }else if(imagetypes()&IMG_WBMP){
                 header("Content-Type:image/vnd.wap.wbmp");
     imagepng($this->image);
     }else
     {
      die("PHP不支持图片验证码");
     }
    }
        //通过该方法向浏览器输出图像
    function  showImage($fontFace="")
    {
     //创建图像背景
            $this->createImage();
     //设置干扰元素
           $this->setDisturbColor();
     //向图像中随机画出文本
     $this->outputText($fontFace);
     //输出图像
     $this->outputImage();
    }

    function __destruct()
    {
     imagedestroy($this->image);
    }
   }
   function checklogin(){
        if(empty($_POST['name']))
                die( '用户名不能为空');
    if(empty($_POST['password']))
     die("密码不能为空");
    if($_SESSION['code']!=$_POST['vertify'])
     die("验证码输入不正确".$_SESSION['code']);
  
    $username=$_POST['name'];
    $password=md5($_POST['password']);
    //检查是否存在
         conndb($username,$password);
   }
   function conndb($name="",$ps=""){
        $conn=mysql_connect('localhost','root','123456');
       if(!$conn) die("数据库连接失败".mysql_error());
     mysql_select_db('5kan',$conn) or die('选择数据库失败'.mysql_error());
  mysql_set_charset('utf8',$conn);
  $sql="select id from k_user where  username='{$name}' and password='{$ps}'";
  $result=mysql_query($sql) or die("SQL语句错误".mysql_error());
  if(mysql_num_rows($result)>0)  die("登录成功");
  else  die("用户名或者密码错误");
  mysql_close($conn);
   }
    session_start();
   if(!isset($_POST['randnum']))
   {
     $code=new ValidationCode(120,20,4);
     $code->showImage("comicbd.ttf");  //显示在页面
  $_SESSION['code']=$code->getCheckCode();//保存在服务器中
   }
   else
   {
    checklogin();
   }

?>


到具体调用的地方,用这样的形式:<img" width=100% src="/yz.php" align="absmiddle" />就可以了;验证的时候验证session:$_SESSION['VCODE']的值就可以了。还可以对以上代码稍微改进,改成两个数字相加求和的形式

我们会听过这一种句话,在网络上不要相信任何输入信息,我们都必须进行参数过滤,下面我就来介绍过滤分页参数吧,有需要的朋友可参考。

实例

 代码如下 复制代码

$this->load->library ( 'pagination' );
$config ['base_url'] = site_url () . '/guest/show';
$config ['total_rows'] = $c;
$config ['per_page'] = $pernum = 15;
$config ['uri_segment'] = 3;
$config ['use_page_numbers'] = TRUE;
$config ['first_link'] = '第一页';
$config ['last_link'] = '最后一页';
$config ['num_links'] = 5;
$this->pagination->initialize ( $config );
if (! $this->uri->segment ( 3 )) {
    $currentnum = 0;
} else {
    $currentnum = is_numeric($this->uri->segment ( 3 ))?(intval($this->uri->segment ( 3 ) - 1)) * $pernum:0;
}
 
$current_page=is_numeric($this->uri->segment ( 3 ))?intval($this->uri->segment ( 3 )):1;
if($current_page){
    $data ['title'] = '第'.$current_page.'页-留言本-大冶实验高中首届宏志班网站';
}
else{
    $data ['title'] = '留言本-大冶实验高中首届宏志班网站';
}
 
$data ['liuyan'] = $this->ly->getLy ( $pernum, $currentnum );

其中:

 代码如下 复制代码

 
$current_page=is_numeric($this->uri->segment ( 3 ))?intval($this->uri->segment ( 3 )):1;
$currentnum = is_numeric($this->uri->segment ( 3 ))?(intval($this->uri->segment ( 3 ) - 1)) * $pernum;

这两句判断了参数是否为数字。防止非法字符输入。

标签:[!--infotagslink--]

您可能感兴趣的文章: