Reputation: 2188
I have been building a php form for some time and have passed through the various stages of validation. I have settled on validating with php. However; I can't figure out how to kill the script or abort submit if validation fails. I would have thought it would be as simple as exit()
Here's where I'm at;
// 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
}
Any push I could get in the right direction would be of great help.
NOTE: I have only included one of my validations as to keep the post a little more compact.
** Answered in chat **
My own stupidity caused this problem. (I was only setting the variables, if they weren't getting called, the script would never reach exit();
thanks for the asssitance all.
Upvotes: 0
Views: 493
Reputation: 1055
I have tried it with exit() or with die() and they both work correctly. This is my code snippet:
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{
.
.
.
}
}
Upvotes: 1