如果reCAPTCHA失败,请保留表单数据

时间:2014-09-08 23:09:34

标签: php recaptcha

我有三个简单的问题,希望有人可以提供帮助:

1)当用户未通过reCAPTCHA测试时,我试图让我的表单保留其数据。我怎样才能做到这一点?我现有的代码如下。

2)从其他类似的StackOverFlow问题,有人建议使用:

value="<?php echo (isset($_POST['first_name']) ? htmlspecialchars($_POST['first_name']) : ''); ?>

这似乎保留了所有字段的数据,除了消息字段,这显然是最重要的:)对于消息字段,我尝试使用以下内容但没有成功:

    value="<?php echo (isset($_POST['message']) ? htmlspecialchars($_POST['message']) : ''); ?>

3)最后,上述代码是否可以安全使用?我知道用户提交表单可能是一个严重的安全威胁。

这是我现有的代码:

<?php
$mail =  get_field('email');
$title = get_the_title();

if(isset(filter_input_array(INPUT_POST)['submit'])){

// check reCAPTCHA information
    require_once('recaptchalib.php');

    $privatekey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ";
    $resp = recaptcha_check_answer ($privatekey,
              $_SERVER["REMOTE_ADDR"],
              filter_input_array(INPUT_POST)["recaptcha_challenge_field"],
              filter_input_array(INPUT_POST)["recaptcha_response_field"]);

    // if CAPTCHA is correctly entered!                       
    if ($resp->is_valid) {          

$to = $mail; // this is your Email address
$from = trim(filter_input_array(INPUT_POST)['email']); // this is the sender's Email address
$first_name = trim(filter_input_array(INPUT_POST)['first_name']);
$last_name = trim(filter_input_array(INPUT_POST)['last_name']);
$contact_number = trim(filter_input_array(INPUT_POST)['contact_number']);
$subject = "Website enquiry";
$subject2 = "Website automated message";
$message ="Message";
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly." . "<br/><br/>";
} else {
        // handle the CAPTCHA being entered incorrectly
        echo "Sorry,  you entered the reCAPTCHA code incorrectly.";
        $_SESSION['form'] = filter_input_array(INPUT_POST);
    }
}
?>

<form action= "#contact-form" method="post">
First Name:<br> <input type="text" name="first_name" ><br>
Last Name:<br> <input type="text" name="last_name"><br>
Contact Number:<br> <input type="text" name="contact_number"><br>
Email:<br> <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<p>Are you a human? Please enter the text in the image below.</p>
<?php
require_once('recaptchalib.php');
$publickey = "xxxxxxxxxxxx";
echo recaptcha_get_html($publickey);
?>
<br/>
<input type="submit" name="submit" value="Submit">
</form>

提前致谢!!

1 个答案:

答案 0 :(得分:-1)

textarea没有value属性。相反,您需要将$_POST['message']中的内容放在开始和结束标记之间:

<textarea rows="5" name="message" cols="30">
    <?php echo htmlspecialchars($_POST['message']); ?>
</textarea>