如何驗證用戶是否使用ajax輸入了正確的驗證碼?並且如果$_POST['captchainput'] != $_SESSION['code']
阻止提交表單。當使用ajax和php提交表單提交時驗證captcha
這是標記
<form action="captchaccept.php" method="POST" name="maincontact"> <input type="text" placeholder="Please enter the code" autocomplete="off" id="captchainput" name="captchainput"> <img src="captcha.php" id="captchaimage"> </form>
captcha.php
`
session_start();
$image_width = 135;
$image_height = 30;
$characters_on_image = 8;
$font = 'captchafont/acmesa.ttf';
$possible_letters = '23456789abcdfghjkmnpqrstvwxyz';
$random_dots = 10;
$random_lines = 30;
$captcha_text_color="0x142864";
$captcha_noice_color = "0x142864";
$code = '';
$i = 0;
while ($i < $characters_on_image) {
$code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
$i++;
}
$_SESSION['code'] = $code;
$font_size = 14;
$image = @imagecreate($image_width, $image_height);
$background_color = imagecolorallocate($image, 255, 255, 255);
$arr_text_color = hexrgb($captcha_text_color);
$text_color = imagecolorallocate($image, $arr_text_color['red'],
$arr_text_color['green'], $arr_text_color['blue']);
$arr_noice_color = hexrgb($captcha_noice_color);
$image_noise_color = imagecolorallocate($image, $arr_noice_color['red'],
$arr_noice_color['green'], $arr_noice_color['blue']);
for($i=0; $i<$random_dots; $i++) {
imagefilledellipse($image, mt_rand(0,$image_width),
mt_rand(0,$image_height), 2, 3, $image_noise_color);
}
$textbox = imagettfbbox($font_size, 0, $font, $_SESSION['code']);
$x = ($image_width - $textbox[4])/2;
$y = ($image_height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $_SESSION['code']);
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
function hexrgb ($hexstr) {
$int = hexdec($hexstr);
return array("red" => 0xFF & ($int >> 0x10),
"green" => 0xFF & ($int >> 0x8),
"blue" => 0xFF & $int);
}`
captchaaccept.php
` 在session_start();
if(isset($_SESSION['code'])) {
if(empty($_POST['captchainput']) === false) {
if($_SESSION['code'] === $_POST['captchainput']) {
echo 'ok';
}
}
}`
有人可以教我如何使用Ajax驗證這個驗證碼?或只是告訴我一個例子,在此先感謝:)
你張貼在這裏什麼是工作的罰款? –
這是一個關於AJAX,PHP,Captchas的教程http://webcheatsheet.com/php/create_captcha_protection.php – zer02
是它的工作正常,但我想要的是通過使用ajax它會自動驗證,如果$ _POST和$ _SESSION是用戶提交表單後相同,如果不相等,則會阻止表單提交併顯示錯誤消息 – peace