PHP生成图片验证码

结合网上资料,初次写出来了~~

<?php
  	// 设置session
    session_start(); 
    // 设置验证码生成几位
    $num = 4;
    // 设置宽度
    $width = 100;
    // 设置高度
    $height = 30;
    //生成验证码,也可以用mt_rand(1000,9999)随机生成
     $Code = ""; 
     for ($i = 0; $i < $num; $i++) { 
        $Code .= mt_rand(0,9); 
     } 

    // 将生成的验证码写入session
    $_SESSION['Code'] = $Code;

    // 设置头部
    header("Content-type: image/png");

    // 创建图像(宽度,高度)
    $img = imagecreate($width,$height);

    //创建颜色 (创建的图像,R,G,B)
    $GrayColor = imagecolorallocate($img,230,230,230);
    $BlackColor = imagecolorallocate($img, 0, 0, 0);
    $BrColor = imagecolorallocate($img,52,52,52);

    //填充背景(创建的图像,图像的坐标x,图像的坐标y,颜色值)
    imagefill($img,0,0,$GrayColor);

    //设置边框
    imagerectangle($img,0,0,$width-1,$height-1, $BrColor);

    //随机绘制两条虚线 五个黑色,五个淡灰色
    $style = array ($BlackColor,$BlackColor,$BlackColor,$BlackColor,$BlackColor,$GrayColor,$GrayColor,$GrayColor,$GrayColor,$GrayColor);  
    imagesetstyle($img, $style);
    imageline($img,0,mt_rand(0,$height),$width,mt_rand(0,$height),IMG_COLOR_STYLED);
    imageline($img,0,mt_rand(0,$height),$width,mt_rand(0,$height),IMG_COLOR_STYLED);

    //随机生成干扰的点
    for ($i=0; $i < 200; $i++) {
        $PointColor = imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
        imagesetpixel($img,mt_rand(0,$width),mt_rand(0,$height),$PointColor);
    }

    //将验证码随机显示
    for ($i = 0; $i < $num; $i++) {
        $x = ($i*$width/$num)+mt_rand(5,12);
        $y = mt_rand(5,10);
        imagestring($img,7,$x,$y,substr($Code,$i,1),$BlackColor); 
    }

    //输出图像
    imagepng($img);
    //结束图像
    imagedestroy($img);
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值