我寻找过类似的问题,但没有找到我的具体案例。
我正在我拥有的表单中使用 PHP Captcha 插件。我处理不正确和正确的验证码条目的方式非常相似。如果用户的短语正确,我会抛出一个 javascript“成功”警报,发送表单电子邮件,然后将其发送回最后一页。如果不正确,我会抛出一个 javascript“您的错误”警报,并将它们发送回最后一页。
我的问题 - 如果它们不正确,我需要刷新验证码,因为如果验证码输入不正确,您将始终需要刷新图像以进行另一次尝试。另外,如果它们正确,我希望清除该字段,但仅在正确时清除,如果不正确,我想保留表单数据。我怎样才能做到这一点?
这是我的 PHP 验证码,以便您可以看到我的尝试。如果您想要 html,请告诉我...(我还在 POST 之前用 JS 检查了所有条目)
<?php
/*set email*/
$myemail = "email@email.com";
/* Check all form inputs using check_input function */
$name = $_POST['name'];
$companyName = $_POST['companyName'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$TimeForContact = $_POST['TimeForContact'];
$aval = $_POST['aval'];
$messageFromFrom = $_POST['message'];
$firstTime = $_POST['firstTime'];
$subject = "Some Subject";
require_once('recaptcha-php-1.11/recaptchalib.php');
$privatekey = "*someprivatekey*"; //I took this out for the question
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
echo '<script type="text/javascript"> alert ("You have inserted the wrong phrase in the Captcha box. Please try again! Thank you."); window.history.back();</script>';
exit();
} else {
$message = "some message
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
echo '<script type="text/javascript"> alert ("Success! You have emailed your submission. Please await our response. Thank you."); window.history.back()</script>';
exit();
}
?>
我最初尝试通过JS重新加载页面,例如:
window.reload(history.back());
或
window.location.reload(history.go(-1));
任何一个+类似的多个组合都没有成功。
重申一下这个问题:
如何在需要时刷新表单/验证码
或者
您提交验证码表单的习惯行为是什么?
谢谢。
最佳答案
你应该做这样的事情。本质上是检查错误并将错误推送到错误数组中,您可以稍后循环并显示给用户。提交后,您检查验证码,如果无效,它将自动清除该字段。不要使用警报或 exit() 或任何类似的东西,一个简单的 $errors 数组就足够了。
//untested code
<?php
//check to make sure they submitted the form
if(isset($_POST['submit'])){
$errors = array();
$myemail = "email@email.com";
$name = $_POST['name'];
$companyName = $_POST['companyName'];
/* ... */
//recaptcha check
require_once('recaptcha-php-1.11/recaptchalib.php');
$privatekey = "*someprivatekey*";
$resp = recaptcha_check_answer (
$privatekey,$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]
);
//validate all data here
if (!$resp->is_valid) {
array_push($errors, "recaptcha invalid please try again");
}else if( /* name is invalid */) {
array_push($errors, "name invalid");
}else if (){
/* keep validing ...... with else if*/
}
/*....*/
else{
//everything validated so were good
mail($myemail, $subject, $message);
}
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form action="process.php">
<!-- Your form here, "process.php" is this page itself -->
<input name="submit" type="submit" value="Send">
</form>
</body>
</html>
关于php - 使用 PHP Captcha 插件的 HTML 表单,我遇到了一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15991312/