• 技术文章 >php教程 >php手册

    如何运用PHP GD库生成验证码

    2016-06-13 11:05:50原创555

    当我们要使用先在php.ini里增加一行引用:extension=php_gd2.dll

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

    表单auth.html

    1. <html>
    2. <head>
    3. <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
    4. <title>验证码title>
    5. head>
    6. <body>
    7. <h1>请输入验证码h1>
    8. <form action="check_auth.php" method="post">
    9. <input name="auth" type="text">
    10. <img src="auth.php" border="0" />
    11. <input type="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库生成验证码的相关知识,希望对大家有所帮助。


    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    上一篇:PHP面向对象编程的基础知识讲解 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • php利用新浪接口查询ip获取地理位置• php mysql 数据库类• PHP代码:Http断点续传的实现例子• 如何获知PHP程序占用多少内存(memory_get_usage)• PHP Memcached应用实现代码
    1/1

    PHP中文网