php验证码操作

验证码 的基础操作

首先需要确保php环境开启了gd库,如何开启查看百度

在thinkphp环境下编写

先看视图界面

很简单的表单页面  , 
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript">
    function test1 () {
        var simg=document.getElementById('simg').src="__URL__/gd/?r=<?php echo rand() ?>";
    }
    </script>
</head>
<body>
<form action="__URL__/gd2">
<img src="__URL__/gd/?r=<?php echo rand() ?>" id="simg">
    <input type="text" name="code" >
    <a href="javascript:void(0)" onclick="test1()">看不清?</a>
    <input type="submit" value="提交">
</form>
</body>
</html>

控制器层

 public function gd(){

    // 宽和高100*30像素
    $images=imagecreatetruecolor(100,30);  
    // 背景图
    $bgcolor=imagecolorallocate($images, 255, 255, 255) ;
    imagefill($images,100,10,$bgcolor);

$code="";
    for($i=0;$i<4;$i++){
        $fontsize=10;  //字体大小
        // 增加复杂  添加字符和数字配合
        // 字体颜色随机  最好控制0~120之间, 因为该区间颜色是深色范围
        $fontcolor=imagecolorallocate($images, rand(0,120), rand(0,120),rand(0,120));
        // 随机数字
        $fontcontent=rand(0,9);

        // 随机数字和字母
        $data="abcdefghijklmnopqrstuvwxyz0123456789";
        $fontcontent=substr($data,rand(0,strlen($data)),1);
        $code.=$fontcontent;
        // x,y轴随机

        $x=($i*100/4)+rand(5,10);
        $y=rand(5,10);
        // 水平画一条线
        imagestring($images, $fontsize, $x, $y, $fontcontent, $fontcolor);
    }
// 多台服务器可以使用memcache保存数据
$_SESSION['auth_code']=$code;



// 接着添加干扰素  干扰线和干扰点


// 干扰点设置
    for($i=0;$i<200;$i++){
            $pointcolor=imagecolorallocate($images, rand(50,200), rand(50,200), rand(50,200)) ;
            // 随机点
            imagesetpixel($images,rand(1,99),rand(1,99),$pointcolor);
    }

    // 干扰线设置
    for($i=0;$i<3;$i++){
            $lincolor=imagecolorallocate($images, rand(50,250), rand(50,250), rand(50,250)) ;
            // 随机线
            imageline($images, rand(1,99), rand(1,29), rand(1,99), rand(1,29), $lincolor);


    }

    // 在输出图片前面必须先输出header

    header("Content-type:image/png");
    imagepng($images);
    imagedestroy($images);
    exit;
    }

业务处理

 public function gd2(){
    if(trim(strtolower($_REQUEST['code']))==$_SESSION['auth_code']){
        echo "输入正确";
    }
    else{
        echo "输入失败";
    }
    $this->display();
   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值