说明:一些基本的代码我都进行了注释,这里实现的验证码位数、须要用的字符串均可以再设置。有个人注释,你们应该很容易能看得懂。php
基本思路:浏览器
1.用mt_rand()随机生成数字肯定须要获取的字符串,对字符串进行拼接(以为生成的验证码以为有点太挤,你们能够再字符串中间拼接个空格键),实现随机验证码;spa
备注:建议你们用mt_rand(),而不是rand(),前者效率更高code
2.利用gd库生成图片,把随机字符串写到图片输出。blog
效果:图片
每次刷新,都生成一个随机验证,后期我可能还会补充怎么实现随机码点击图片就再次更新资源
代码:字符串
<?php // 建立画布
$width = 120; // 规定画布的宽高
$height = 45; $image = imagecreatetruecolor($width, $height); // 建立一幅真彩色图像 // 添加一些即将用到的颜色
$white = imagecolorallocate($image, 0xf2, 0xec, 0xe0); $orange = imagecolorallocate($image, 0xff, 0xa5, 0x4c); // 对画布背景填充颜色
imagefill($image, 0, 0, $white); //mt_rand 获取随机数 mt_rand(min, max);
function str_rand(){ $str="abcdefghijkmnpqrstuvwxyz0123456789ABCDEFGHIGKLMNPQRSTUVWXYZ"; $rand=""; for($i=0; $i<5; $i++){//获取5个随机的字符串
$rand .= $str[mt_rand(0, strlen($str)-1)]; //如:随机数为30 则:$str[30]
} return $rand; } $verifyCode=str_rand(); // 画一串字符串在画布上
imagestring($image, 10, 10, 10, "$verifyCode", $orange); // 通知浏览器输出的是图像(png类型)
header('Content-Type: image/png'); // 输出到浏览器
imagepng($image); // 释放图像资源