【发布时间】:2015-07-28 17:07:59
【问题描述】:
如何验证用户是否使用 ajax 输入了正确的验证码?如果$_POST['captchainput'] != $_SESSION['code'],则阻止表单提交。
这是标记
<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>
验证码.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的教程webcheatsheet.com/php/create_captcha_protection.php
-
是的,它工作正常,但我想要的是通过使用 ajax,它会在用户提交表单后自动验证 $_POST 和 $_SESSION 是否相同,如果它不相等,它将阻止表单提交并显示错误信息
-
您好,欢迎来到 Stackoverflow!您可以通过解释更多您想要的内容来改进您的问题:“使用 AJAX 验证”是什么意思? “防止表单提交”是什么意思?此外,我认为 captcha.php 的代码根本没有用 - 您应该删除它,除非您的问题与此代码有特定关系。
标签: php ajax validation captcha