PHP实现验证码功能
大家好我是山河,今天我来分享一个经典案例——-实现PHP验证码功能
首先开启GD库扩展
php.ini里面找到
然后上代码
开启之后
上代码
<?php //author:shanhe //开启session session_start(); //默认返回的是黑色的照片 $image = imagecreatetruecolor(100, 30); //将背景设置为白色的 $bgcolor = imagecolorallocate($image, 255, 255, 255); //将白色铺满地图 imagefill($image, 0, 0, $bgcolor); //author:shanhe //空字符串,每循环一次,追加到字符串后面 $shanhe_user=''; // 62个混合码 function coderand($lentn) { $fontcontent = 'ABCDEFGHIJKLNMOPQRSTUVWXYZ01234567890abcdefghijklnmopqrstuvwxyz'; mt_srand(); $strcode = ''; for($i=0;$i<$lentn;$i++) { $strcode .=$fontcontent[rand(0,61)]; } return $strcode; } //验证码为随机四个数字或者字母 for ($i=0; $i < 4; $i++) { $fontsize=7; $fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120)); //产生随机数字或者字母 //调用函数 $fontcontents = coderand(1); //记录信息 $shanhe_user.= $fontcontents; //数字的位置 $x=($i*100/5)+rand(5,10); $y=rand(5,10); imagestring( $image,$fontsize,$x,$y,$fontcontents,$fontcolor); } // 记录信息 $_SESSION['shanhewebsite'] = $shanhe_user; //验证码背景点干扰元素 for ($i=0; $i < 200; $i++) { $pointcolor = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200)); imagesetpixel($image, rand(1,99), rand(1,29), $pointcolor); } //author:shanhe //https://blog.shanhe.info //验证码划线干扰元素 for ($i=0; $i < 5; $i++) { $linecolor = imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,220)); imageline($image, rand(1,99), rand(1,29),rand(1,99), rand(1,29) ,$linecolor); } // 告诉浏览器这是图片,并生成图片 header('content-type:image/png'); imagepng($image); //销毁 imagedestroy($image); ?>
然后调用即可
实例效果图
本文为山河博客原创文章出品
代码下载: