php 验证码详细生成与使用方法

注意:以下代码需要打开php的gd库,修改php.in文件的配置,把已经注释掉的行之前的分号取消即可:extension=php_gd2.dll.

实例一,代码如下:

  1. $width = 165;
  2. $height = 120;
  3. $image = imagecreatetruecolor($width,$height);
  4. $bg_color = imagecolorallocate($image,255,255,255);
  5. $tm = imagecolorallocate($image,255,0,0);
  6. imagefilledrectangle($image,0,0,$width,$height,$bg_color);
  7. imagefill($image,0,0,$bg_color);
  8. /*
  9. //$text = random_text(5);
  10. $text = "ffff";
  11. $font = 8;
  12. $struft=iconv("gbk","utf-8",$text);
  13. $x = imagesx($image);
  14. $y = imagesy($image);
  15. $fg_color = imagecolorallocate($image,233,14,91);
  16. imagestring($image,$font,$x,$y,$struft,$fg_color);
  17. $_session['captcha'] = $text;
  18. */
  19. header("content-type:image/png");
  20. imagepng($image);
  21. imagedestroy($image);

实例二,代码如下:validate.php

采用了session识别,稍微改进了一下目前网络上流传的php验证码,加入杂点,数字颜色随机显示,控制4位数字显示.

  1. <?php
  2. session_start();
  3. //生成验证码图片
  4. header("content-type: image/png");
  5. $im = imagecreate(44,18);
  6. $back = imagecolorallocate($im, 245,245,245);
  7. imagefill($im,0,0,$back); //背景
  8. srand((double)microtime()*1000000);
  9. //生成4位数字
  10. for($i=0;$i<4;$i++){
  11. $font = imagecolorallocate($im, rand(100,255),rand(0,100),rand(100,255));
  12. $authnum=rand(1,9);
  13. $vcodes.=$authnum;
  14. imagestring($im, 5, 2+$i*10, 1, $authnum, $font);
  15. }
  16. for($i=0;$i<100;$i++) //加入干扰象素
  17. { //开源代码phpfensi.com
  18. $randcolor = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
  19. imagesetpixel($im, rand()%70 , rand()%30 , $randcolor);
  20. }
  21. imagepng($im);
  22. imagedestroy($im);
  23. $_session['vcode'] = $vcodes;
  24. ?>

下面看完整实例,代码如下:

  1. <?php
  2. @header("content-type:text/html; charset=utf-8");
  3. //打开session
  4. session_start();
  5. ?>
  6. <html>
  7. <head>
  8. <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  9. <title>php验证码示例</title>
  10. </head>
  11. <body>
  12. 验证码:<br/>
  13. <iframe height="100" width=300 src="img.php" frame ></iframe>
  14. <br/>
  15. <input type=button value="看不清,换一张" onclick="iimg.location.reload();">
  16. <br>
  17. <form action="validate.php" method="post">
  18. 输入验证码:<input name="imgid" >
  19. <input type="submit" value="确定">
  20. </form>
  21. </body>
  22. </html>

php判断用户输入的验证码是否与系统生成的一致,代码如下:

  1. <?php @header("content-type:text/html; charset=utf-8");
  2. //开启session
  3. session_start();
  4. //得到用户输入的验证码,并转换成大写
  5. $imgid_req = $_request['imgid'];
  6. $imgid_req = strtoupper($imgid_req);
  7. //验证该字符串是否注册了session变量
  8. if (session_is_registered($imgid_req)) {
  9. echo "<font color=blue >通过验证!</font>";
  10. } else {
  11. echo "<font color=red >验证错误!</font>";
  12. }
  13. //关闭session,以清除所有注册过的变量
  14. session_destroy();
  15. ?>