在建站程序中,很多時候都會需要用戶驗證驗證碼等操作,比如:注冊、登錄、發表評論、獲取資源等等,一方面可以驗證當前用戶的行為是否是爬蟲、機器人等情況,給網站資料統計產生影響;另一方面可以防止用戶大量刷取資源導致服務器資源緊張甚至宕機;現在驗證碼在表單中的應用越來越多了,但是如果用js來實作總覺得不太方便,因此可以使用php來實作,
測驗地址:http://api.hmiwin.top/api/yzm.php
請求引數:num,text
引數說明:其中num是欲輸出驗證碼的字符個數;text是欲輸出驗證碼圖片里面的內容
php原始碼如下:
<?php
//http://api.hmiwin.top/api/yzm.php
$num = $_GET['num'];
$text = $_GET['text'];
if($num=="")//如果num引數為空默認等于4
$num = 4;
check_code(150, 50, $num ,$text);//呼叫,其中$num是欲輸出驗證碼的字符個數,$text是欲輸出驗證碼圖片里面的內容
function check_code($width , $height , $num , $string ,$type = 'jpeg' ) {
$img = imagecreate($width, $height);
for ($i = 0; $i < $num; $i++) {
$rand = mt_rand(0, 2);
switch($rand) {
case 0:
$ascii = mt_rand(48, 57);
break;
case 1:
$ascii = mt_rand(65, 90);
break;
case 2:
$ascii = mt_rand(97, 122);
break;
}
$string .= sprintf('%c', $ascii);
}
imagefilledrectangle($img, 0, 0, $width, $height, randBg($img));
for ($i = 0; $i < 50; $i++) {
imagesetpixel($img, mt_rand(0, $width), mt_rand(0, $height), randPix($img));
}
for ($i = 0; $i < $num; $i++) {
$x = floor($width/$num) *$i + 2;
$y = mt_rand(0, $height - 15);
imagechar($img, 5, $x, $y, $string[$i], randPix($img));
}
$func = 'image' . $type;
$header = 'content-type:image/' . $type;
if (function_exists($func)) {
header($header);
$func($img);
} else {
exit('不支持');
}
imagedestroy($img);
return $string;
}
function randBg($img) {
return imagecolorallocate($img, mt_rand(130, 255), mt_rand(130, 255), mt_rand(130, 255));
}
function randPix($img) {
return imagecolorallocate($img, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
}
?>
歡迎轉載,轉載請申明來源地址!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/464115.html
標籤:PHP
