About_PHP_验证码的生成

验证码就是一张图片,用到几个关键字:

 1 <?php
 2 
 3 session_start();
 4 $arr = array(
 5     'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x',
 6     'y','z','0','1','2','3','4','5','6','7','8','9'
 7 );
 8 $rand = "";
 9 for($i=1;$i<=4; $i++){
10     $rand .= $arr[rand(0,count($arr)-1)];
11 }
12 $_SESSION['check_pic'] = $rand;
13 //生成图片
14 $im = imagecreatetruecolor(100,30);
15 
16 //生成颜色,当第一次调用生成颜色的方法,是生成背景颜色(三原色)
17 $bg = imagecolorallocate($im,0,0,0);
18 
19 //第二次调用这个方法,是可以生成图片上面的文字或其他样式的颜色(三原色)
20 $te = imagecolorallocate($im,255,255,255);
21 
22 //在图片上面生成文字
23 //rand(1,5):随机5种字体1-5
24 //rand(3,70):随机文字出现的X轴坐标
25 //rand(3,15):随机文字出现的Y轴坐标
26 //$rand:随机出现的字
27 //$te:采用字体颜色
28 imagestring($im,rand(1,5),rand(3,70),rand(3,15),$rand,$te);
29 
30 //要把php当成图片输出,必须给文件一个头申明,jpeg
31 header("Content-type:image/jpeg");
32 
33 //最终生成图片
34 imagejpeg($im);
35 
36 ?>

 

通常,验证码是需要验证的:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>

<?php
session_start();
if(isset($_POST['check'])){
    if($_POST['check'] == $_SESSION['check_pic']){
        echo "验证成功";
    }else{
        echo "验证失败";
    }
}
?>

<form action="check2.php" method="post">
    <input type="text" name="check"/>
    <img src="check1.php" alt="" onclick="refreshImg()" id="chk" style="cursor: pointer"/>
    <br/>

    <input type="submit" value="提交"/>
</form>
<script>
function refreshImg(){
//    声明一个rand,是为了防止除谷歌以外的不兼容刷新问题
    var rand = Math.round(Math.random()*10000);
    var chk = document.getElementById("chk");
    chk.src = "check1.php?num="+rand;
}
</script>
</body>
</html>

 

随机一个有数字和字母的字符串:

 1 $Arr = array(
 2 'q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m',
 3 '1','2','3','4','5','6','7','8','9','0'
 4 );
 5 $rand="";
 6 
 7 for($i=1;$i<=4;$i++){
 8 $rand.= $Arr[rand(0,count($Arr)-1)];
 9 }
10 echo $rand;

 

posted @ 2014-05-14 00:03  moemiss  阅读(206)  评论(0编辑  收藏  举报