php 使用GD库生成验证码

GD库是PHP进行图象操作一个很强大的库。

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

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

表单auth.html

< html >
< head >
< meta  http-equiv ='Content-Type'  content ='text/html;  charset =utf-8' >
< title > 验证码 </ title >
</ head >
< body >
< h1 > 请输入验证码 </ h1 >
< form  action ="check_auth.php"  method ="post" >
   
< input  name ="auth"  type ="text" >
   
< img  src ="auth.php"  border ="0"   />
   
< input  type ="submit"  value ="提交" >
</ form >
</ body >
</ html >

 

生成验证码 auth.php

<? php
   
session_start ();
   
header ( " Content-type:image/png " );

   
$img_width = 100 ;
   
$img_height = 20 ;

   
srand ( microtime () * 100000 );
   
for ( $i = 0 ; $i < 4 ; $i ++ )
   {
        
$new_number .= dechex ( rand ( 0 , 15 ));
   }

   
$_SESSION [check_auth] = $new_number ;
   
$new_number = imageCreate( $img_width , $img_height ); // 创建图象
   ImageColorAllocate( $new_number , 255 , 255 , 255 );   // 设置背景色为白色

   
for ( $i = 0 ; $i < strlen ( $_SESSION [check_auth]); $i ++ )
   {
       
$font = mt_rand ( 3 , 5 );
       
$x = mt_rand ( 1 , 8 +   $img_width * $i / 4 ;
       
$y = mt_rand ( 1 , $img_height / 4 );
       
$color = imageColorAllocate( $new_number , mt_rand ( 0 , 100 ) , mt_rand ( 0 , 150 ) , mt_rand ( 0 , 200 )); // 设置字符颜色
       imageString( $new_number , $font , $x , $y , $_SESSION [check_auth][ $i ] , $color ); // 输出字符
   }

   ImagePng(
$new_number );
   ImageDestroy(
$new_number );
?>

 

提交页面 check_auth.php

<? php
   
session_start ();
   
$auth = $_POST [ ' auth ' ];

   
if ( empty ( $auth ))
   {
       
echo   ' 错误:验证码不能为空 ' ;
       
die ;
   }

   
if ( $auth == $_SESSION [ ' check_auth ' ])
   {
       
echo   ' 正确 ' ;
   }
   
else
   {
       
echo   ' 错误:验证码输入错误 ' ;
   }
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值