PHP头条
热点:

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


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

  • PHP获取当前url的具体方法介绍
  • PHP程序员最容易出现的错误总结
  • PHP获取远程URL的实例讲解
  • PHP伪静态的四种方法总结
  • PHP实现伪静态化页面的具体实现方式
先在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库生成验证码的相关知识,希望对大家有所帮助。

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

相关文章

    暂无相关文章
相关频道:

PHP之友评论

今天推荐