我已经构建了一个php表单已经有一段时间了,并且已经通过了验证的各个阶段。我已经决定用php验证了。然而;如果验证失败,我无法弄清楚如何终止脚本或中止提交。我原以为它会像exit()
在这里,我在哪里;
// condition
$cont = '';
$msg = '';
// define variables and set to empty values
$fnameErr = $lnameErr = $titleErr = $emailErr = $dayErr = $monthErr = $timeErr = $chkErr = "";
$fnameField = $lnameField = $titleField = $emailField = $daySelect = $monthSelect = $timeSelect = $chk = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["time"])) {
$timeErr = "Please select a time from the list";
exit();
} else {
$timeSelect = test_input($_POST["time"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['btn-sub'])) {
// code executed on submit
$headers = "From: $emailField\r\n";
$headers .= "Content-type: text/html\r\n";
$success = mail($emailAcc, $emailSub, $body, $headers);
if(!$success) {
$cont = "<b>Fatal Error:</b> Mail was not sent successfully.";
exit();
} else {
$cont = "Success! Thank you! <br/> We'll see you there...";
$msg = "Someone will be in touch with you shortly to confirm your details. Please check the supplied informaiton is correct below;";
}
} else {
// code executed on first request
}
任何我能朝正确方向前进的推动都会有很大的帮助。
注意: 我只提供了一个验证,以使帖子更紧凑。
**在聊天中回答**
我自己的愚蠢导致了这个问题。 (我只是设置变量,如果它们没有被调用,那么脚本永远不会到达exit();
,感谢所有的变量。
答案 0 :(得分:1)
我已尝试使用exit()或die(),它们都能正常工作。这是我的代码段:
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//validate post variable != empty
if (empty($_POST['name'])|| empty($_POST['lastname'])|| empty($_POST['email'])|| empty($_POST['phone']) ||empty($_POST['cellphone']) ||empty($_POST['dir']))
{
$response = json_encode(array("error" => "true","message" => "Error, please fill all the form data"));
echo $response;
exit();
}else{
.
.
.
}
}