< SPAN> Header("Content-type:image/png"); //定义header,声明图片文件,最好是png,无版权之扰; //生成新的四位整数验证码 session_start();//开启session; $authnum_session = ''; $str = 'abcdefghijkmnpqrstuvwxyz1234567890'; //定义用来显示在图片上的数字和字母; $l = strlen($str); //得到字串的长度; //循环随机抽取四位前面定义的字母和数字; for($i=1;$i<=4;$i++) { $num=rand(0,$l-1); //每次随机抽取一位数字;从第一个字到该字串最大长度, //减1是因为截取字符是从0开始起算;这样34字符任意都有可能排在其中; $authnum_session.= $str[$num]; //将通过数字得来的字符连起来一共是四位; } session_register("authnum_session"); //用session来做验证也不错;注册session,名称为authnum_session, //其它页面只要包含了该图片 //即可以通过$_SESSION["authnum_session"]来调用
//生成验证码图片, srand((double)microtime()*1000000); $im = imagecreate(50,20);//图片宽与高; //主要用到黑白灰三种色; $black = ImageColorAllocate($im, 0,0,0); $white = ImageColorAllocate($im, 255,255,255); $gray = ImageColorAllocate($im, 200,200,200); //将四位整数验证码绘入图片 imagefill($im,68,30,$gray); //如不用干扰线,注释就行了; $li = ImageColorAllocate($im, 220,220,220); for($i=0;$i<3;$i++) {//加入3条干扰线;也可以不要;视情况而定,因为可能影响用户输入; imageline($im,rand(0,30),rand(0,21),rand(20,40),rand(0,21),$li); } //字符在图片的位置; imagestring($im, 5, 8, 2, $authnum_session, $white); for($i=0;$i<90;$i++) {//加入干扰象素 imagesetpixel($im, rand()%70 , rand()%30 , $gray); } ImagePNG($im); ImageDestroy($im); ?>
验证码调用文件sessionValidate.php
以下是代码片段: <?php session_start(); //在页首先要开启session, //error_reporting(2047); session_destroy(); //将session去掉,以每次都能取新的session值; //用seesion 效果不错,也很方便 ?> <html> <head> <title>session 图片验证实例title> head> <body> 此例为session验证实例 <form action="" method="post"> 验证码:<input type="text" name="validate" value="" size=10> <img src="checkNum_session.php"><br> <input type="submit"> form> php //打印上一个session; echo "上一个session:".$_SESSION["authnum_session"]." "; $validate=""; if(isset($_POST["validate"])){ $validate=$_POST["validate"]; echo "您刚才输入的是:".$_POST["validate"]." 状态:"; if($validate!=$_SESSION["authnum_session"]){ //判断session值与用户输入的验证码是否一致; echo "输入有误"; }else{ echo "通过验证"; } } /* //打印全部session; PrintArr($_SESSION); function PrintArr($aArray){ echo ' ';<BR><img alt="" onload="if(this.width>500) {this.resized=true; this.width=500;}" onmouseover="this.style.cursor='hand'" onclick="{window.open('http://img1.ph.126.net/eG3S7fJMJcmGoBsbcJv77Q==/3190800335993944572.jpg');}" src="http://img1.ph.126.net/eG3S7fJMJcmGoBsbcJv77Q==/3190800335993944572.jpg" align=top>print_r(  ?$aArray);<BR><img alt="" onload="if(this.width>500) {this.resized=true; this.width=500;}" onmouseover="this.style.cursor='hand'" onclick="{window.open('http://img1.ph.126.net/eG3S7fJMJcmGoBsbcJv77Q==/3190800335993944572.jpg');}" src="http://img1.ph.126.net/eG3S7fJMJcmGoBsbcJv77Q==/3190800335993944572.jpg" align=top>echo ' '; } */ ?> | |
评论