3、驗證碼
封裝的驗證碼類?
<?php
/*
* 生成驗證碼
*/
class
Captcha
{
private
$_width
= 100;
private
$_height
= 25;
private
$_number
= 4;
//顯示的驗證碼的字符個數
private
$_font
= 15;
//驗證碼字體大小
private
$_fontfile
=
'STXINWEI.TTF'
;
//創建驗證碼圖像
public
function
makeImage()
{
# 1. 創建圖像資源(畫布)
$image
= imagecreatetruecolor(
$this
->_width,
$this
->_height);
//隨機填充顏色
//mt_rand(0,255) 生成一個更具有唯一性的隨機數 #000 255
$color
= imagecolorallocate(
$image
,mt_rand(100,255),mt_rand(100,255),mt_rand(100,255));
imagefill(
$image
,0,0,
$color
);
# 2.繪制文字
$code
=
$this
-> makeCode();
//隨機生成驗證碼文字 ab3g
$color
= imagecolorallocate(
$image
,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
for
(
$i
=0;
$i
<
$this
->_number;
$i
++){
imagettftext(
$image
,
$this
->_font,mt_rand(-30,30),
$i
*(
$this
->_width/
$this
->_number)+5,20,
$color
,
$this
->_fontfile,
$code
[
$i
]);
}
# 3.繪制15條干擾線條
for
(
$i
=0;
$i
<10;
$i
++){
$color
= imagecolorallocate(
$image
,mt_rand(100,150),mt_rand(100,150),mt_rand(100,150));
imageline(
$image
,mt_rand(0,
$this
->_width),mt_rand(0,
$this
->_height),mt_rand(0,
$this
->_width),mt_rand(0,
$this
->_height),
$color
);
}
# 4.設置100個干擾像素點
for
(
$i
=0;
$i
<100;
$i
++){
imagesetpixel(
$image
,mt_rand(0,
$this
->_width),mt_rand(0,
$this
->_height),
$color
);
}
# 5.將驗證碼保存起來嗎,便于后面再其他地方使用
//只能使用session來存儲,session明天就會講到
session_start();
$_SESSION
[
'captcha'
] =
$code
;
//在瀏覽器輸出、顯示一下
header(
"Content-Type:image/png"
);
imagepng(
$image
);
imagedestroy(
$image
);
}
/**
* 隨機產生隨機數
*/
public
function
makeCode()
{
# 獲得字母的范圍(大寫字母、小寫字母)
$lower
= range(
'a'
,
'z'
);
//創建從小a到小z字符范圍的數組
$upper
= range(
'A'
,
'Z'
);
//創建從大A到大Z范圍的數組
$number
= range(3,9);
//創建從3到9之間的數字
//將上面的三個數組合并成一個數組
$code
=
array_merge
(
$lower
,
$upper
,
$number
);
# 打亂數組元素的順序
shuffle(
$code
);
//隨機從上面的數組中篩選出n個字符,需要通過下標來取數組的元素
$str
=
''
;
for
(
$i
=0;
$i
<
$this
->_number;
$i
++){
$str
.=
$code
[
$i
];
}
return
$str
;
}
/**
* 驗證用戶輸入的驗證碼和我們生產的驗證碼是否一致
* @param [str] $input [輸入驗證碼值]
* @return
*/
public
function
checkCode(
$input
)
{
session_start();
if
(
strtolower
(
$code
) ==
strtolower
(
$_SESSION
[
'captcha'
])){
//說明驗證碼正確
//echo '驗證碼正確';
return
true;
}
else
{
//echo '驗證碼錯誤';
return
false;
}
}
}
?>
實例 - 驗證碼驗證(結合上面的驗證類)
html頁面?
<
form
action
=
"captcha.php?act=verify"
method
=
"post"
>
驗證碼:<
input
type
=
"text"
name
=
"captcha"
>
<
img
src
=
"captcha.php?act=show"
>
<
br
>
<
input
type
=
"submit"
value
=
"提交"
>
</
form
>
驗證碼檢測 captcha.php 頁面?
//接收地址欄上面的參數
if
(
$_GET
[
'act'
]==
'verify'
){
//說明是提交的表單
//接收表單中用戶輸入的內容
$code
=
$_POST
[
'captcha'
];
//和創建的驗證碼進行比較
session_start();
//將用戶輸入的驗證碼 和 我們創建的統一小寫之后再進行比較
if
(
strtolower
(
$code
) ==
strtolower
(
$_SESSION
[
'captcha'
])){
//說明驗證碼正確
echo
'驗證碼正確'
;
}
else
{
echo
'驗證碼錯誤'
;
}
}
else
if
(
$_GET
[
'act'
]==
'show'
){
//說明需要顯示一個圖片
require
'Captcha.class.php'
;
$captcha
=
new
Captcha();
$captcha
-> makeImage();
}
分享到:
投訴收藏