php生成图片验证码

来源:互联网 发布:瓦森纳协议知乎 编辑:程序博客网 时间:2024/05/22 03:15

在我们的网站,系统的开发中经常的会使用到图片的验证码,虽然这种方式,在逐渐的被替代;但是对于一些小型的网站和系统来说,仍然可以算作是一种比较好的方式;

下面是以php的代码实现一种图片验证码,在使用过程中,我们只需要将图片的src指向这个php文件即可;

代码:

<?phpsession_start ();//首先开启session //以下三项均可通过前台传递参数进行修改$sessionkey = "chkcode";//默认验证码的key$width = 75; // 验证码图片的宽度,默认$height = 23; // 验证码图片的高度,默认 if (isset ( $_GET ["key"] ) && ! empty ( $_GET ["key"] )) {    $sessionkey = $_GET ["key"];} if (isset ( $_GET ["width"] ) && ! empty ( $_GET ["width"] )) {    $width = $_GET ["width"];} if (isset ( $_GET ["height"] ) && ! empty ( $_GET ["height"] )) {    $height = $_GET ["height"];} //生成字符串function random($len) {    $srcstr = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";//我们把0和O去掉了,防止出现不宜区分    mt_srand ();    $strs = "";    for($i = 0; $i < $len; $i ++) {        $strs .= $srcstr [mt_rand ( 0, 33 )];    }    return strtoupper ( $strs );} $str = random ( 4 ); // 随机生成的字符串--4位的长度,可以根据实际情况修改$_SESSION [$sessionkey] = $str; // 放入session @header ( "Content-Type:image/png" );//设定以png的图片格式输出$im = imagecreate ( $width, $height );//大小$back = imagecolorallocate ( $im, 0xFF, 0xFF, 0xFF ); // 背景色$pix = imagecolorallocate ( $im, 187, 230, 247 ); // 模糊点颜色$font = imagecolorallocate ( $im, 132, 163, 227 ); // 字体色mt_srand (); // 绘模糊作用的点-加噪点for($i = 0; $i < 800; $i ++) {    imagesetpixel ( $im, mt_rand ( 0, $width ), mt_rand ( 0, $height ), $pix );}imagestring ( $im, 6, 17, 4, $str, $font );imagepng ( $im );imagedestroy ( $im );?>


这样就生成了一个验证码图片,同时在session中保存了其值,如果需要验证时,只需要将前台输入的内容同session中的值进行比对即可。

转载请注明:http://itsshq.com/article-223.html

0 0
原创粉丝点击