平常,在注册账号和登入网站的时候,都会用到验证码。那个验证码多是图片显示的,并且乱乱的,要闪瞎你的眼睛。点击验证码还要能刷新。

先来看下下边的验证码效果吧。

看过了,那么今天就来制作制作验证码吧。

为了达到闪瞎眼睛的目的,下边一步一步的开始生成验证码图片吧。

(a)先生成一个长方形的底色。

(b)再在底色上生产随机的几条线线,这个线条是随机颜色随机位置的。

(c)再随机生成一些小雪花,这些小雪花就是*号,用imagestring来生,大小为1,位置和颜色随机。为了防止雪花影响了正在的验证码,雪花的颜色用浅一点的,就是rgb的200以后的数字。

(d)再产生一个四位数字和字母的组合,这里为了方便,直接生成0到15之间的数字,然会用转化成16进制,再转化成大写(大写看着舒服)。为什么是四位数字呢,四位看起来简单又不简单。当然你可以更长或更短。

(e)将产生的数字字母组合写到图片上。四个字母的位置是随机的,颜色也是随机的。为了防止字母溢出图片所在范围,可以适当的调整随机坐标范文。

(f)生成的验证码不仅要让用户看到,还要页面知道。这里,可以用session来记录,因为cookie会慢一拍。

(g)最后,点击验证码图片能够实现刷新的功能。毕竟生成的验证码有时候不是很好辨认,用户可以点击验证码来刷新。刷新验证码是js来实现的,也就是img标签的点击事件。点击了,让img的src更新一次,指向的还是原来的url,不过后边会加一个随机数。让它知道是新的。

好了,现在来上代码吧。

html页面,这里只输入一个验证码图片,用img标签,img的点击事件,用到js。在这里,单独创建一个js,并包含进来。

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>非你网丶非你不可</title>
<script type ="text/javascript" src = "js/code.js"></script>
</head>
<body>
    <img src="code.php" alt="验证码" id = "code" /><br/>
</body>
</html>

 

code.js

window.onload = function()
{
    document.getElementById('code').onclick = function()
    {
        this.src = "code.php?time=" + (new Date().getTime());
    }
}

 

code.php

<?php
    
header("Content-type:image/png");
_code();

function _code($width = 75 , $height =25 , $numOfcode = 4)
{
    $img = imagecreatetruecolor($width,$height);
    $bgColor = imagecolorallocate($img ,255,255,255);
    imagefill($img, 0, 0, $bgColor);

    for($i =0 ; $i<6 ; $i++)
    {
        $randColor = imagecolorallocate($img, mt_rand(0,255), mt_rand(0, 255), mt_rand(0, 255));
        imageline($img, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $randColor);
    }

    for($i =0 ; $i <100 ; $i++)
    {
        $randColor = imagecolorallocate($img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
        imagestring($img, 1, mt_rand(0, $width), mt_rand(0, $height), '*', $randColor);
    }

    $code = "";
    for($i =0 ; $i <$numOfcode ; $i++)
    {
        $code .= dechex(mt_rand(0,15));
    }
    $code = strtoupper($code);

    for($i =0 ; $i< $numOfcode ; $i++)
    {
        $txtColor = imagecolorallocate($img, mt_rand(0,100),mt_rand(0, 150), mt_rand(0, 200));
        imagestring($img, 5, ($width/$numOfcode * $i + mt_rand(0, 10)), mt_rand(0, $height/2),substr($code,$i,1), $txtColor);
    }

    imagepng($img);
    imagedestroy($img);
    
    session_start();
    $_SESSION['code'] = $code;
}

?>