php使用for循环生成4位验证码只生成了3位
巴扎黑
巴扎黑 2017-04-10 17:03:33
[PHP讨论组]

我是用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);
?>


上图为生成效果

巴扎黑
巴扎黑

全部回复(2)
PHPz

1个可能的原因

$fontcontent = substr($data,rand(0,strlen($data)),1);

这里改为

$fontcontent = substr($data,rand(0,strlen($data)-1),1);

原因是phprand方法为闭区间,前后分别为最小值和最大值,都可以出现

ringa_lee

试试strlen($data)-1

$fontcontent = substr($data,rand(0,strlen($data)),1);这行

艾玛我点进来的时候还没有回复。跟楼上雷同,我不是故意的。
大家给楼上点赞吧。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号