PHP基础-如何实现验证码

<?php
/**
 * Created by PhpStorm.
 */

session_start();
$chars = '23456789ABCDEFGHJKLMNPRSTWXY';
$string = '';
for($i=0; $i<4; $i++)
{
    $rand1 = rand(0,strlen($chars)-1); // 减1是为了避免出现3位的验证码,例如随机数为最后一个字符
    $string .= substr($chars,$rand1,1);

}
//echo $string."<br>";   在header前不能有任何输出,否则出现错误
$_SESSION['string'] = $string;

$image_width = 120;
$image_height = 30;
$im = imagecreate($image_width,$image_height);
$back_color = imagecolorallocate($im,rand(220,255),rand(220,255),rand(220,255));
imagefilledrectangle($im,0,0,$image_width,$image_height,$back_color);

for($i=0; $i<100; $i++)
{
    $dot_color = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
    $x = rand(0,$image_width);
    $y = rand(0,$image_height);
    imagesetpixel($im,$x,$y,$dot_color);
}

for($i=0; $i<strlen($string); $i++)
{
    $font_color = imagecolorallocate($im,rand(0,120),rand(0,120),rand(0,120));
    imagestring($im,10, rand(20*$i+1,20*$i+10),rand(0,8),substr($string,$i,1),$font_color);
}
header('Content-type:image/x-png');
imagepng($im);
imagedestroy($im);
exit();

猜你喜欢

转载自blog.csdn.net/modern358/article/details/89631087
今日推荐