我是用php for循环生成验证码,经常出现有一位验证码没能生成的情况,希望了解问题的大神的帮忙看下代码,非常感谢!
<?php
$image = imagecreatetruecolor(100,30);
$bgcolor = imagecolorallocate($image,255,255,255);
imagefill($image,0,0,$bgcolor);
// 生成干扰像素点
for ($i=0; $i < 200; $i++) {
$pixelcolor = imagecolorallocate($image,rand(121,254),rand(121,254),rand(121,254));
imagesetpixel($image,rand(1,99),rand(1,29),$pixelcolor);
}
// 生成干扰直线
for ($i=0; $i < 4; $i++) {
$linecolor = imagecolorallocate($image,rand(121,254),rand(121,254),rand(121,254));
imageline($image,rand(0,99),rand(0,29),rand(0,99),rand(0,29),$linecolor);
}
//生成验证码
for ($i=0; $i < 4; $i++) {
$fontsize = 6;
$fontcolor = imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
$data = 'abcdefghijkmnpqrstuvwxy3456789';
$fontcontent = substr($data,rand(0,strlen($data)),1);
$x = ($i*100/4)+rand(5,10);
$y = rand(5,10);
imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);
}
header('content-type:image/png');
imagepng($image);
imagedestroy($image);
?>

上图为生成效果
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
1个可能的原因
这里改为
原因是
php的rand方法为闭区间,前后分别为最小值和最大值,都可以出现试试
strlen($data)-1?在
$fontcontent = substr($data,rand(0,strlen($data)),1);这行艾玛我点进来的时候还没有回复。跟楼上雷同,我不是故意的。
大家给楼上点赞吧。