PHP联系表单验证字段

时间:2014-02-12 16:57:12

标签: php forms security verification

使用下面的脚本(取自模板),我添加了一个简单的验证问题来防止垃圾邮件(什么是2 + 2?)。截至目前,当填写提交按钮时,将显示error.php页面,但表单将作为空白提交。

如何确保仅在验证安全问题后提交表单?

<?php

$EmailTo = "myemail@email.com";
$Subject = "website";
$name = Trim(stripslashes($_POST['name'])); 
$email = Trim(stripslashes($_POST['email'])); 
$number = Trim(stripslashes($_POST['number'])); 
$message = Trim(stripslashes($_POST['message'])); 

// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.php\">";
  exit;
}

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $number;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";

// send email 
$submit = mail($EmailTo, $Subject, $Body, "From: <$email>");

// redirect to success page 
if(isset($_POST['submit'])){
if(isset($_POST['answer']) && $_POST['answer'] == 4){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.php\">";
}
}
?>

表格代码如下:

<div id="form-holder" class="cont">
                        <h2>Contact form</h2>
                    <form method="post" action="send.php" class="uniform get-in-touch">

                    <div class="i-h">
                    <input type="text" name="name" id="name"/>
                    <div class="i-l"><span>Name</span></div></div>

                    <div class="i-h">
                    <input type="email" name="email" id="email"/>
                    <div class="i-l"><span>E-mail</span></div></div>

                    <div class="i-h">
                    <input type="text" name="number" id="number"/>
                    <div class="i-l"><span>Number</span></div></div>

                    <div class="t-h">
                    <textarea name="message" rows="32" cols="8" id="message" placeholder="Please leave us a message."></textarea>
                    </div>

                    <br><p>What is 2+2?</p><input type="text" name="answer" id="answer" />

                    <input type="submit" name="submit" value="Submit" class="submit-button">
                            <a href="#" class="do-clear">Clear</a>
                </form>
                    </div>

2 个答案:

答案 0 :(得分:0)

如果您正在为HTML5构建,则可以使用required属性。

<br><p>What is 2+2?</p><input type="text" name="answer" id="answer" required/>

答案 1 :(得分:0)

另一种选择是纯PHP:

if( !empty( $_POST['answer'] ) && $_POST['answer'] == 4) {
     // send email 
     $submit = mail($EmailTo, $Subject, $Body, "From: <$email>");
} else {
     // Set error
     echo "Verification failed.";
}