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

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

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

#t#先在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.  
  5.    $img_width=100;  
  6.    $img_height=20;  
  7.  
  8.    srand(microtime()*100000);  
  9.    for($i=0;$i<4;$i++)  
  10.    {  
  11.         $new_number.=dechex(rand(0,15));  
  12.    }  
  13.  
  14.    $_SESSION[check_auth]=$new_number;  
  15.    $new_number=imageCreate($img_width,$img_height);//创建图象  
  16.    ImageColorAllocate($new_number,255,255,255);  //设置背景色为白色  
  17.  
  18.    for($i=0;$i<strlen($_SESSION[check_auth]);$i++)  
  19.    {  
  20.        $font=mt_rand(3,5);  
  21.        $x=mt_rand(1,8) + $img_width*$i/4;  
  22.        $y=mt_rand(1,$img_height/4);  
  23.        $color=imageColorAllocate($new_number,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200));//设置字符颜色  
  24.        imageString($new_number,$font,$x,$y,$_SESSION[check_auth][$i],$color);//输出字符  
  25.    }  
  26.  
  27.    ImagePng($new_number);  
  28.    ImageDestroy($new_number);  
  29. ?> 

PHP GD库提交页面 check_auth.php

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

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

责任编辑:曹凯 来源: 博客园
相关推荐

2015-09-21 15:31:05

php实现验证码

2012-05-24 15:41:38

PHP

2009-12-11 15:17:52

PHP验证码调用

2009-11-23 16:59:23

PHP图形验证码

2009-11-26 10:48:59

PHP验证码

2024-01-29 08:32:10

Python验证码识别

2024-03-08 12:04:22

PythonPillow验证码

2020-12-29 05:33:03

Serverless验证码架构

2013-06-19 10:19:59

2010-01-08 13:46:30

VB.NET中文验证码

2022-02-11 07:10:15

验证码

2021-01-19 10:29:34

短信验证码密码

2017-12-21 07:38:19

2015-03-23 17:58:04

验证码倒计时并行

2010-01-11 14:16:14

VB.NET生成验证码

2020-11-16 07:28:53

验证码

2009-08-11 14:05:28

JSP验证码

2009-02-09 14:17:36

2011-11-02 16:46:41

点赞
收藏

51CTO技术栈公众号