最近学校学习任务需要用到验证码,敲完代码后运行时发现验证码并没有生效,上官网查看才发现原来是自己的GD库没有配置,需要我们对php.ini文件进行配置
1、载入GD库
在php.ini文件中写入extension=php_gd.dll
2、在php.ini文件中开启gd.jpeg_ignore_warning,这个值为1或者0都可以没有影响,也可以不开启
验证码代码如下
<?php//必须至于顶部,多服务器端记录验证码信息,便于用户输入后做校验session_start();//默认返回的是黑色的照片$image = imagecreatetruecolor(200, 50);//将背景设置为白色的$bgcolor = imagecolorallocate($image, 255, 255, 255);//将白色铺满地图imagefill($image, 0, 0, $bgcolor);//空字符串,每循环一次,追加到字符串后面$captch_code='';//验证码为随机四个数字for ($i=0; $i < 5; $i++) {$fontsize=12;$fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));//产生随机数字0-9$fontcontent = rand(0,9);$captch_code.= $fontcontent;//数字的位置,0,0是左上角。不能重合显示不完全$x=($i*200/5)+rand(5,10);$y=rand(5,10);imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);}$_SESSION['authcode'] = $captch_code;//为验证码增加干扰元素,控制好颜色,//点for ($i=0; $i < 200; $i++) {$pointcolor = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));imagesetpixel($image, rand(1,199), rand(1,49), $pointcolor);}//为验证码增加干扰元素//线for ($i=0; $i < 10; $i++) {$linecolor = imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,220));imageline($image, rand(1,199), rand(1,49),rand(1,199), rand(1,49) ,$linecolor);}header('content-type:image/png');imagepng($image);//销毁imagedestroy($image);