PHP實現驗證碼

2021-04-17 13:00:20 字數 2495 閱讀 5894

目前,不少**為了防止使用者利用機械人自動註冊、登入、灌水,都採用了驗證碼技術。所謂驗證碼,就是將一串隨機產生的數字或符號,生成一幅,裡加上一些干擾象素(防止

ocr),由使用者肉眼識別其中的驗證碼資訊,輸入表單提交**驗證,驗證成功後才能使用某項功能。

我們這裡展示了如何編寫

php程式實現驗證碼功能:

**一:

<?php

/* *filename:authpage.php

*author:hutuworm

*date:2003-04-28

*@copylefthutuworm.org

*/ srand((double)microtime()*1000000);

//驗證使用者輸入是否和驗證碼一致

//生成新的四位整數驗證碼

while(($authnum=rand()%10000)<1000);

?>

**二:

<?php

/* *filename:authimg.php

*author:hutuworm

*date:2003-04-28

*@copylefthutuworm.org

*/ //

生成驗證碼

header("content-type: image/png");

srand((double)microtime()*1000000);

$im = imagecreate(58,28);

$black = imagecolorallocate($im, 0,0,0);

$white = imagecolorallocate($im, 255,255,255);

$gray = imagecolorallocate($im, 200,200,200);

imagefill($im,68,30,$gray);

//將四位整數驗證碼繪入

加入干擾象素

imagepng($im);

imagedestroy($im);

?>

本文程式在

apache 2.0.45 + php 4.3.1

環境下執行通過。

上文只是對驗證碼功能的乙個簡單實現,並沒有考慮商用安全性問題。如果要增強安全性,將此功能投入商業應用,則可以通過以下幾個步驟實現:

1. 啟用session。

2. authnum

在authimg.php

中生成,並計算

md5sum

,存入session。

3. authpage.php

將authinput

計算md5sum

後,與session

中的authnum

(md5sum

)對比得出驗證結果。

本站注:作者使用了簡單的**實現了很酷的功能。不過在新增干擾畫素時的效果不是太好,大家可以看一下雨聲論壇登入時的效驗碼

,偶把第二段**稍改了一下,生成了與其類似的效果。

修改後的**如下:

<?php

/* *filename: authimg.php

*author:hutuworm

*date:2003-04-28

*@copyleft hutuworm.org

*/ //

生成驗證碼

header("content-type: image/png");

srand((double)microtime()*1000000);

$im = imagecreate(62,20);

$black = imagecolorallocate($im, 0,0,0);

$white = imagecolorallocate($im, 255,255,255);

$gray = imagecolorallocate($im, 200,200,200);

imagefill($im,68,30,$gray);

while(($authnum=rand()%100000)<10000);

//將四位整數驗證碼繪入

imagestring($im, 5, 10, 3, $authnum, $black);

for($i=0;$i<200;$i++)//

加入干擾象素

imagepng($im);

imagedestroy($im);

?>

php實現驗證碼

繪製驗證碼 num 5 str getcode num,2 建立畫布 width num 20 height 30 im imagecreatetruecolor width,height color 0 imagecolorallocate im,100,18,199 color 1 imagec...

PHP實現驗證碼

建立並設定大小 image imagecreatetruecolor 100,30 設定驗證碼顏色 方法 imagecolorallocate 物件,int red,int green,int blue bgcolor imagecolorallocate image,190,234,239 設定為...

php 驗證碼實現

width 80 height 28 image imagecreatetruecolor width,height white imagecolorallocate image,255,255,255 白色 black imagecolorallocate image,0,0,0 黑色 用填充矩形...