php 基础简单案例 点击随机切换验证码
效果图
html代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
</head>
<body>
<div style="width: 400px; height: 200px; margin: 300px auto">
<img src="01-CAPTCHA_image.php" onclick="this.src='01-CAPTCHA_image.php?src=' + Math.random()">
</div>
</body>
</html>
php代码如下
<?php
header('Content-type:image/png');
//创建图片资源
$img = imagecreatetruecolor(200, 50);
//添加背景色
$bg_color = imagecolorallocate($img, 220, 220, 220);
imagefill($img, 0, 0, $bg_color);
$font = 'simhei.ttf';
//获取随机颜色
function getRandomColor($img)
{
return ImageColorAllocate($img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
}
//定义随机文字
$str = '安徽法律界艾斯芬尼率拉上覅来挖矿饭窘境发哦舒服就好金卡文件发哦';
$len = strlen($str) / 3; //获取字符长度
//随机汉字数
$char = substr($str, mt_rand(0, $len - 1) * 3, 3);
$char1 = substr($str, mt_rand(0, $len - 1) * 3, 3);
//写入文字
$str_color = imagecolorallocate($img, mt_rand(0, 100), mt_rand(0, 200), mt_rand(0, 250));
$str_color1 = imagecolorallocate($img, mt_rand(0, 100), mt_rand(0, 200), mt_rand(0, 250));
imagettftext($img, mt_rand(15, 30), mt_rand(-15, 15), 60, mt_rand(25, 35), $str_color, $font, $char);
imagettftext($img, mt_rand(15, 30), mt_rand(-15, 25), 120, mt_rand(25, 35), $str_color1, $font, $char1);
//生成干扰点
for ($i = 0; $i < 50; $i++) {
imagestring($img, mt_rand(1, 5), mt_rand(0, 200), mt_rand(0, 50), '&', getRandomColor($img));
}
//生成干扰线
for ($i = 0; $i < 10; $i++) {
imageline($img, mt_rand(0, 200), mt_rand(0, 50), mt_rand(0, 200), mt_rand(0, 50), getRandomColor($img));
}
//输出资源
imagepng($img);
//销毁资源
imagedestroy($img);