php編程——驗證碼的實現(session方法)

index.php(實現輸入驗證碼頁面)代碼如下:

<html>
<head>
<title>check code</title>
</head>
<body>
<form name=check method=post action=check.php>
<input type=hidden name=init value=1>
驗證碼:<input type=text name=code maxlength=4 style="width=50px;">

<!--得到驗證碼圖片-->
<img src=image.php>

<p>
<input type=submit value="提交">
</form>
</body>
</html>




image.php(驗證碼生成頁面)代碼如下:

<?php
session_start();
srand((double)microtime()*1000000); 
$authnum=rand(1000,9999);
session_register("authnum");
header("content-type:image/png");
        function creat_image($width,$height,$authnum)
        {
                srand((double)microtime()*1000000); 
                $im = imagecreate($width,$height); 
                $black = ImageColorAllocate($im, 0,0,0); 
                $white = ImageColorAllocate($im, 255,255,255); 
                $gray = ImageColorAllocate($im, 200,200,200); 
                imagefill($im,0,0,$gray);

                //將四位整數驗證碼繪入圖片 
                imagestring($im, 5, 10, 3, $authnum, $black); 
                for($i=0;$i<200;$i++)   //加入干擾象素 
                {         
                    $randcolor = ImageColorallocate($im,rand(0,255),rand(0,255),rand(0,255));
                    imagesetpixel($im, rand()%70 , rand()%30 , $randcolor); 
                } 
                ImagePNG($im); 
                ImageDestroy($im); 
        }
creat_image(60,20,$authnum);
?>




check.php(驗證界面)代碼如下:

<?php
session_start();

if(!isset($init)) $init=0;
if($init)
{
 if($_POST['code']==$authnum)
 {
  echo "驗證碼正確!";
 }

 else echo "驗證碼錯誤,請重新輸入!";
}
else echo "調用頁面錯誤!"
?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章