2012年5月23日星期三

【转】php 最简单的验证码

摘自:http://www.oschina.net/code/snippet_203819_7926

01create_code.php
02<?php
03session_start();
04 //生成验证码图片
05header("Content-type: image/png");
06// 全数字
07$str = "1,2,3,4,5,6,7,8,9,a,b,c,d,f,g";      //要显示的字符,可自己进行增删
08$list = explode(",", $str);
09$cmax = count($list) - 1;
10$verifyCode = '';
11for ( $i=0; $i < 5; $i++ ){
12      $randnum = mt_rand(0, $cmax);
13      $verifyCode .= $list[$randnum];           //取出字符,组合成为我们要的验证码字符
14}
15$_SESSION['code'] = $verifyCode;        //将字符放入SESSION中
16  
17$im = imagecreate(58,28);    //生成图片
18$black = imagecolorallocate($im, 0,0,0);     //此条及以下三条为设置的颜色
19$white = imagecolorallocate($im, 255,255,255);
20$gray = imagecolorallocate($im, 200,200,200);
21$red = imagecolorallocate($im, 255, 0, 0);
22imagefill($im,0,0,$white);     //给图片填充颜色
23  
24//将验证码绘入图片
25 imagestring($im, 5, 10, 8, $verifyCode, $black);    //将验证码写入到图片中
26  
27for($i=0;$i<50;$i++)  //加入干扰象素
28{
29     imagesetpixel($im, rand()p , rand()0 , $black);    //加入点状干扰素
30     imagesetpixel($im, rand()p , rand()0 , $red);
31     imagesetpixel($im, rand()p , rand()0 , $gray);
32     //imagearc($im, rand()p, rand()p, 20, 20, 75, 170, $black);    //加入弧线状干扰素
33     //imageline($im, rand()p, rand()p, rand()p, rand()p, $red);    //加入线条状干扰素
34}
35imagepng($im);
36imagedestroy($im);
37?>
38 引用
39demo.html
40<!-- DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd" -->
42<head>
43    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
44    <title></title>
45</head>
46 
47<body>
48<form action="act.php" method="post">
49<input type="text" name="code" />
50<img id="code" src="create_code.php" alt="看不清楚,换一张" style="cursor: pointer; vertical-align:middle;" onClick="create_code()"/>
51<!--<button type="button" onClick="create_code()">更换</button>-->
52<button type="submit">提交</button>
53</form>
54<script>
55 function create_code(){
56     document.getElementByIdx_x('code').src = 'create_code.php?'+Math.random()*10000;
57}
58</script>
59 </body>
60</html>
61//处理,判断是否输入正确
62act.php
63 <?php
64session_start();
65 
66 if($_POST['code'] == $_SESSION['code']){
67    echo 'ok';
68}else{
69    echo 'no';
70}
71?>

没有评论: