php验证码的封装和使用

来源:互联网 发布:java堆栈溢出怎么解决 编辑:程序博客网 时间:2024/06/05 09:11

1.首先我们先来封装一个验证码的函数方法,方便使用
考虑一下我们要传什么参数
接下来看代码解释

<?php/***@prame int $width*@prame int $height*@prame int $type*@prame int $num*@prame $tring *author wulei*/function yanzhengma($width = 100,$height = 30,$type = 1,$num = 4,$imgType = 'png'){    //创建一个画布    $image = imagecreatetruecolor($width,$height);    //判断验证吗是那种类型    switch($type){        case 1:            $str = "0123456789";            $string = substr(str_shuffle($str),0,$num);            break;        case 2:            $arr = range('a','z');            shuffle($arr);            $string = join('',array_slice($arr,0,$num));            break;        case 3:            $str = '123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';            $string = substr(str_shuffle($str),0,$num);            break;    }    //给画布添加颜色    imagefilledrectangle($image,0,0,$width,$height,lightColor($image));    //画像素点    for($i=0;$i<50;$i++){        imagesetpixel($image,mt_rand(0,$width),mt_rand(0,$height),darkColor($image));    }    //画干扰线    for($i=0;$i<5;$i++){        imagearc($image,mt_rand(20,$width-20),mt_rand(10,$height),mt_rand(10,$width),mt_rand(10,$height), mt_rand(0 , 20) , mt_rand(45,230) , darkColor($image));    }    //画文字    for($i=0;$i<$num;$i++){        $x = ($width/$num)*$i+10;        $y = mt_rand(10,$height-20);        imagechar($image , 5 , $x , $y , $string[$i] , darkColor($image));    }    //mime类型    header("Content-type:image/$imgType");    //输出    $func = 'image'.$imgType;     if(!function_exists($func)){        return false;    }    $func($image);    //销毁    imagedestroy($image);    return $string;}//封装一个浅颜色function lightColor($image){    $color = imagecolorallocate($image , mt_rand(130 , 255),mt_rand(130,255),mt_rand(130,255));    return $color;}function darkColor($image){    $color = imagecolorallocate($image,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120));    return $color;}

2.方法封装好了,接下来看一下html 显示的样子

<html><head>    <meta charset = "utf-8"/></head><body>    <form action = "register.php" method = "post">        <input type = "text" name ="mima" value = ""/>        <img src = "code.php" onclick = "this.src = 'code.php?'+Math.random()" id ="image"/>        <a href = "javascript:;" id = "btn">换一张</a>        <input type = "submit" value = "提交"/>    </form>    <script>        var oImg = document.getElementById('image');        var oBtn = document.getElementById('btn');        oBtn.onclick = function(){            oImg.src = 'code.php?'+Math.random();        }    </script></body>

3.将封装的验证码方法返回值存在session中(注意要先开启session)

<?phpsession_start();include '封装的函数文件';$_SESSION['code'] = yanzhengma();

4.接收input传过来的值 与session来对比

<?phpsession_start();if(strtolower($_SESSION['code']) == strtolower($_POST['mima'])){    echo '成功';}else{    echo '失败';}