PHP生成验证码

<?php
/**
 * Created by PhpStorm.
 * User: lin
 * Date: 2017/6/20
 * Time: 13:47
 */
/*主要思想就是生成一张图片,然后将随机生成的字符填充进去,之后向图片里填充一些线条和点。主要用到了 GD图像函数,需要激活 GD 支持 */
session_start();
define('CAPTCHA_NUMCHARS',6);//验证码字符个数
define('CAPTCHA_WIDTH',100);//图片验证码宽度
define('CAPTCHA_HEIGHT',25);//图片验证码高度
$pass_phrase = "";
for($i=0;$i<CAPTCHA_NUMCHARS;$i++){
    $pass_phrase.=chr(rand(97,122)); //生成验证码
    /*
     * chr($) : 返回相对应于 ascii 所指定的单个字符
     * rand ( int $min , int $max ) : 返回$min-$max 之间的一个随机数
     *  */
}

$SESSION['pass_phrase'] = sha1($pass_phrase);//将随机出来的验证码存到会话中

/*
 *resource imagecreate ( int $x_size , int $y_size )
 *imagecreate() 返回一个图像标识符,代表了一幅大小为 x_size 和 y_size 的空白图像。
 * */

$img = imagecreate(CAPTCHA_WIDTH,CAPTCHA_HEIGHT);//创建图像
/*
 int imagecolorallocate ( resource $image , int $red , int $green , int $blue )
 imagecolorallocate() 返回一个标识符,代表了由给定的 RGB 成分组成的颜色。red,green 和 blue 分别是所需要的颜色的红,绿,蓝成分。
这些参数是 0 到 255 的整数或者十六进制的 0x00 到 0xFF。imagecolorallocate() 必须被调用以创建每一种用在 image 所代表的图像中的颜色。
 * */
$bg_color = imagecolorallocate($img,255,255,255);//定义背景颜色
$text_color = imagecolorallocate($img,0,0,0);//定义文字颜色
$graphic_color = imagecolorallocate($img,64,64,64);//定义填充线条颜色

imagefilledrectangle($img,0,0,CAPTCHA_WIDTH,CAPTCHA_HEIGHT,$bg_color);//将图片背景颜色设置为$bg_color
/*bool imagefilledrectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
imagefilledrectangle() 在 image 图像中画一个用 color 颜色填充了的矩形,其左上角坐标为 x1,y1,右下角坐标为 x2,y2。0, 0 是图像的最左上角。*/
for($i=0;$i<5;$i++){
    imageline($img,0,rand()%CAPTCHA_HEIGHT,CAPTCHA_WIDTH,rand()%CAPTCHA_HEIGHT,$graphic_color);
    /*bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
imageline() 用 color 颜色在图像 image 中从坐标 x1,y1 到 x2,y2(图像左上角为 0, 0)画一条线段。*/
}

for($i=0;$i<50;$i++){
    imagesetpixel($img,rand()%CAPTCHA_WIDTH,rand()%CAPTCHA_HEIGHT,$graphic_color);
    /*bool imagesetpixel ( resource $image , int $x , int $y , int $color )
imagesetpixel() 在 image 图像中用 color 颜色在 x,y 坐标(图像左上角为 0,0)上画一个点。*/
}
//imagestring($img,5,75,75,$pass_phrase,$text_color);
imagettftext($img,18,0,5,CAPTCHA_HEIGHT-5,$text_color,"./Courier New Bold.ttf",$pass_phrase);//将生成的验证码写入到图像中
/*array imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )
使用 TrueType 字体将 指定的 text 写入图像。*/
header("Content-type:image-png");
//echo $pass_phrase;
imagepng($img);//在浏览器上显示图片

imagedestroy($img);//释放内存中的图像

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值