PHP GD库是PHP进行图像操作时的一个非常重要的库,我们下面就通过介绍PHP GD库生成验证码的方法来进一步加深对它的了解。

当我们要使用PHP进行图像操作的时候,必然会使用到一个PHP GD库,它是一个很强大的库。今天我们要向大家介绍的就是PHP GD库如何生成验证码的相关方法。

如何运用PHP GD库生成验证码(PHP生成验证码)  PHP GD库 第1张

#t#先在PHP.ini里增加一行引用:extension=php_gd2.dll

重启apache。做一个测试页 var_dump(gd_info());输出数据表明PHP GD库引用成功。

表单auth.html

  1. <html>
  2. <head>
  3. <metahttp-equiv='Content-Type'content='text/html;charset=utf-8'>
  4. <title>验证码</title>
  5. </head>
  6. <body>
  7. <h1>请输入验证码</h1>
  8. <formaction="check_auth.php"method="post">
  9. <inputname="auth"type="text">
  10. <imgsrc="auth.php"border="0"/>
  11. <inputtype="submit"value="提交">
  12. </form>
  13. </body>
  14. </html>

PHP GD库生成验证码 auth.php

  1. <?php
  2. session_start();
  3. header("Content-type:image/png");
  4. $img_width=100;
  5. $img_height=20;
  6. srand(microtime()*100000);
  7. for($i=0;$i<4;$i++)
  8. {
  9. $new_number.=dechex(rand(0,15));
  10. }
  11. $_SESSION[check_auth]=$new_number;
  12. $new_number=imageCreate($img_width,$img_height);//创建图象
  13. ImageColorAllocate($new_number,255,255,255);//设置背景色为白色
  14. for($i=0;$i<strlen($_SESSION[check_auth]);$i++)
  15. {
  16. $font=mt_rand(3,5);
  17. $x=mt_rand(1,8)+$img_width*$i/4;
  18. $y=mt_rand(1,$img_height/4);
  19. $color=imageColorAllocate($new_number,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200));//设置字符颜色
  20. imageString($new_number,$font,$x,$y,$_SESSION[check_auth][$i],$color);//输出字符
  21. }
  22. ImagePng($new_number);
  23. ImageDestroy($new_number);
  24. ?>

PHP GD库提交页面 check_auth.php

  1. <?php
  2. session_start();
  3. $auth=$_POST['auth'];
  4. if(empty($auth))
  5. {
  6. echo'错误:验证码不能为空';
  7. die;
  8. }
  9. if($auth==$_SESSION['check_auth'])
  10. {
  11. echo'正确';
  12. }
  13. else
  14. {
  15. echo'错误:验证码输入错误';
  16. }
  17. ?>

以上就是本文所介绍的PHP GD库生成验证码的相关知识,希望对大家有所帮助。

转载请说明出处
知优网 » 如何运用PHP GD库生成验证码(PHP生成验证码)

发表评论

您需要后才能发表评论