怎么用PHP写一个验证码

2025-06-27 23:50:28

1、先写一个函数,验证码为4位,在0-9中随机产生4个酆璁冻嘌function create_captcha($count租涫疼迟=4) { $code=''; $charset='1234567890'; $len=strlen($charset)-1; for($i=0;$i<$count;$i++) { $code.=$charset[rand(0,$len)]; } return $code; }

2、验证码中的干扰线及干扰点,讳求藜派背景颜色及字体的cssfunction captcha_img($code) { $im=imagecreate($x=180, $y=50); image艘早祓胂colorallocate($im, rand(50,200), rand(0,155),rand(0,155)); $fontColor=imagecolorallocate($im, 255, 255, 255); $fontStyle='file/captcha.ttf'; for($i=0,$len=strlen($code);$i<$len;$i++) { imagettftext($im, 30, rand(0,20)-rand(0, 25), 32+$i*40, rand(30,50), $fontColor, $fontStyle, $code[$i]); } for($i=0;$i<8;++$i) { $lineColor=imagecolorallocate($im, rand(0,255), rand(0,255),rand(0,255)); imageline($im, rand(0, $x), 0, rand(0, $x), $y, $lineColor); } for($i=0;$i<250;++$i) { imagesetpixel($im, rand(0, $x), rand(0, $y), $fontColor); } ob_clean(); header('Content-type:image/png'); imagepng($im); imagedestroy($im); }

3、在项目中引用这个验证码<?php session_start(); require './common/captcha.php'; $code=create_captcha(); captcha_img($code); $_SESSION['captcha']=$code;?>

怎么用PHP写一个验证码

4、成品大概是长这个样子,希望大家都能做的出来。

怎么用PHP写一个验证码
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢