PHP-仿ecshop生成验证码

<?php 
/*
    生成验证码
 */
// 1.创建画布(基于已有图像)
$n = mt_rand(1,5);
$im = imagecreatefromjpeg('./images/captcha_bg'.$n.'.jpg');
// 2.创建颜色
$white = imagecolorallocate($im,255,255,255);
$black = imagecolorallocate($im,0,0,0);
// 3.绘制图像
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$len = strlen($chars);
$code = '';
for($i=0;$i<4;$i++){
    $index = mt_rand(0,$len-1);
    // 拼接得到的$code即是验证码上的字符串
    $code .= $chars[$index];
}
// 将验证码保存到session
@session_start();
$_SESSION['captcha_code'] = $code;
// 确定字符串的横纵坐标。使其居中
$imgWidth = imagesx($im);
$imgHeight = imagesy($im);
$fontWidth = imagefontwidth(5);
$fontHeight = imagefontheight(5);
$x = ($imgWidth-$fontWidth*4)/2;
$y = ($imgHeight-$fontHeight)/2;
// 确定字符串颜色。1/3的概率为黑色
if(mt_rand(1,3) == 1){
    $color = $black;
} else {
    $color = $white;
}
// 将字符串写入到图像上
imagestring($im,5,$x,$y,$code,$color);
// 4.输出图像
header('content-type:image/jpeg');
imagejpeg($im);
// 5.销毁图像
imagedestroy($im);

?>

说明:这是仿照ecshop的后台登录页写的一个简单的生成验证码的代码

转载于:https://www.cnblogs.com/mozshaw/p/5378151.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值