When I click the submit button without filling the form, a new entry appears on database with the ID but the form keep validating and showing the user, this field is required but why the form is still submitting to the database?
Here is my code, kindly help, I am new in PHP and very tired of solving such problem.
<?php
include 'dbc.php';
// define variables and set to empty values
$name_error = $email_error = $phone_error = $url_error = $message_error = "";
$name = $email = $phone = $message = $url = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone_error = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
}
if (empty($_POST["url"])) {
$url_error = "Website url is required";
} else {
$url = test_input($_POST["url"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$url)) {
$url_error = "Invalid URL";
}
}
if (empty($_POST["message"])) {
$message_error = "Message field is required";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' and $message_error == ''){
$message = 'Hello Ladies';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message .= "$key: $value\n";
}
$to = 'sample#email.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
}
}
$query = "INSERT INTO clients(name,email,phone,url,message) ";
$query .= "VALUES('$name', '$email', '$phone', '$url', '$message') ";
$create_user = mysqli_query($mysqli, $query);
if (!$create_user) {
die("QUERY FAILED. " . mysqli_error($mysqli));
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I hope I don't get downvote.
The only check actually being made before the query is run, is
if ($_SERVER["REQUEST_METHOD"] == "POST") {
which means that the only requirement for inserting values, is that the form is sent over POST, nothing else. This can be checked with a proper editor and seeing what brackets are wrapped around your query. You do some checks earlier in the code to validate and check the input, but this doesn't tell if the query should be run or not.
If you move the closing-bracket } of the following if-block
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' and $message_error == ''){
until after the query is performed, the query will only run if it passed all your checks. (place it after the following snippet)
if (!$create_user) {
die("QUERY FAILED. " . mysqli_error($mysqli));
}
In other remarks, your test_input() is rubbish (really) and you shouldn't use it. Parameterize your queries instead and filter the input with proper functions. There are validation filters and sanitation filters already implemented in PHP, you should use them if you need to.
You should prepare and bind the values of your queries using mysqli::prepare(), this will handle any issues dealing with quotes and protect your database against SQL injection.
References
mysqli::prepare()
How can I prevent SQL injection in PHP?
Related
This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 4 years ago.
my php contact form works and sends me an email when people fill it out. what is happinging though is when they click submit, the screen goes white and nothing happens. I want the page to refresh or redirect to another page. How Can I get it to refresh?
here is my PHP:
<?php
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'whitandr#oregonstate.edu';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message_body)){
$success = "Message sent, thank you!";
$name = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
You can add this to the end of your script to redirect the user header('Location: success.php');
<?php
$name_error = $email_error = $phone_error = $url_error = $last_name_error= "";
$firstName = $lastName = $email = $phone = $message = $url = $success = "";
if (isset($_POST["sendMessage"])) {
if (empty($_POST["firstName"])) {
$name_error = "Name is required";
} else {
$firstName = test_input($_POST["firstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["lastName"])) {
$last_name_error = "Name is required";
} else {
$lastName = test_input($_POST["lastName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastName)) {
$last_name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone_error = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
$phone_error = "Invalid phone number";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $last_name_error == '' and $email_error == '' and $phone_error == '' ){
$message_body = '';
unset($_POST['sendMessage']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'some#gmail.com';
$subject = 'webmaster#example.com';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstName = $lastName = $email = $phone = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I tried to make this contact form validated. but it doesn't work. whenever i send a email form live server only message is send but name, phone, email don't send. please someone help me. I am working on it since last day but not working.
Thats because you're not sending them at all. Look at your code:
if (mail($to, $subject, $message)){
Yoou're sending the variable $message as message, thats fine.. but, lets have a look whats inside this variable:
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
You're assigning the value of $_POST["message"] to it - nothing else.
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
I think you would send $message_body instead of $message, then it should work fine :)
Hope it help.
I thought of using php header to redirect upon validation successful. However it's seems broken to me. How do I implement one then. Condition is when all the validation is validated then it would only redirect.
<?php
// define variables and set to empty values
$nameErr = $lastnameErr = $emailErr = $passwordErr = $confirmpasswordErr = $checkboxErr= "";
$name = $lastname = $email = $password = $confirmpassword = $checkbox = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$nameErr = "First Name is required";
}else {
$name = test_input($_POST["firstname"]);
}
if (empty($_POST["lastname"])) {
$lastnameErr = "Last Name is required";
}else {
$name = test_input($_POST["lastname"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
}else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if(!empty($_POST["password"]) && ($_POST["password"] == $_POST["confirmpassword"])) {
$password = test_input($_POST["password"]);
$confirmpassword = test_input($_POST["confirmpassword"]);
if (strlen($_POST["password"]) <= '8') {
$passwordErr = "Your Password Must Contain At Least 8 Characters!";
}
elseif(!preg_match("#[0-9]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Number!";
}
elseif(!preg_match("#[A-Z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Capital Letter!";
}
elseif(!preg_match("#[a-z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter!";
}
}
elseif(empty($_POST["password"])) {
$passwordErr = "Password not filled at all";
}
elseif(!empty($_POST["password"])) {
$confirmpasswordErr = "Password do not match";
}
if(!isset($_POST['checkbox'])){
$checkboxErr = "Please check the checkbox";
}
else {
$checkbox = test_input($_POST["checkbox"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
header('Location: http://www.example.com/');
Set $error = 1 if any condition get failed , and at the bottom check if($error!=1) then redirect
and you can also use javascript redirect if header is not working
Look at the closing "?>"-Tab. header will generate a html-header, but is a php-function and should be inside the ?php ?> bracket.
Consider using html5 input validation - saves some code and server roundtrips to let the browser do the validation
Omit the closing "?>" altogether. Its not necessary and can lead to hard to see errors when there is content - even blanks - after the "?>"
Consider using the filter_input function with appropriate parameters to access $_POST and set your variables.
I am new to PHP and currently getting back to HTML. I have made a form and have the data sent and validated by PHP but I am trying to send the email to myself only after the data had been validated and is correct. Currently if the page is loaded I think it send an email and it will send whenever I hit submit without the data being correct.
Here is where I validate the data:
<?php
//Set main variables for the data.
$fname = $lname = $email = $subject = $website = $likedsite = $findoption = $comments = "";
//Set the empty error variables.
$fnameErr = $lnameErr = $emailErr = $subjectErr = $commentsErr = $websiteErr = $findoptionErr = "";
//Check to see if the form was submitted.
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check the 'First Name' field.
if (empty($_POST["fname"]))
{
$fnameErr = "First Name is Required.";
}
else
{
$fname = validate_info($_POST["fname"]);
}
//Check the 'Last Name' field.
if (empty($_POST["lname"]))
{
$lnameErr = "Last Name is Required.";
}
else
{
$lname = validate_info($_POST["lname"]);
}
//Check the 'E-Mail' field.
if (empty($_POST["email"]))
{
$emailErr = "E-Mail is Required.";
}
else
{
$email = validate_info($_POST["email"]);
//Check if valid email.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid E-Mail Format.";
}
}
//Check the 'Subject' field.
if (empty($_POST["subject"]))
{
$subjectErr = "Subject is Required.";
}
else
{
$subject = validate_info($_POST["subject"]);
}
//Check the 'Website' field.
if (empty($_POST["siteurl"]))
{
$website = "";
}
else
{
$website = validate_info($_POST["siteurl"]);
//Check if valid URL.
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL.";
}
}
//Check the 'How Did You Find Us' options.
if (empty($_POST["howfind"]))
{
$findoptionErr = "Please Pick One.";
}
else
{
$findoption = validate_info($_POST["howfind"]);
}
//Check the comment box.
if (empty($_POST["questioncomments"]))
{
$commentsErr = "Questions/Comments are Required.";
}
else
{
$comments = validate_info($_POST["questioncomments"]);
}
//Pass any un-required data.
$likedsite = validate_info($_POST["likedsite"]);
}
function validate_info($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Sorry its a little lengthy.
Here is where I try to send the email. I have tried two different attempts and both have the same result.
<?php
if (!empty($fnameErr) || !empty($lnameErr) || !empty($subjectErr) || !empty($emailErr) || !empty($commentErr) || !empty($websiteErr) || !empty($findoptionErr))
{
echo "Sent!!";
}else
{
echo"Not Sent!!";
}
//Make the message.
$message =
"
First Name: $fname.\n
Last Name: $lname.\n
Website: $website\n
Did They Like the Site? $likedsite.\n
How They Found Us. $findoption.\n
Question/Comments:\n
$comments.
";
$message = wordwrap($message, 70);
$headers = "From: $email";
mail("me#gmail.com", $subject, $message, $headers);
?>
Once again sorry for the length. Thanks in advance also sorry if this is a double question or not described enough I am also new to stack overflow.
Please try:
<?php
//Set main variables for the data.
$fname = $lname = $email = $subject = $website = $likedsite = $findoption = $comments = "";
//Set the empty error variables.
$fnameErr = $lnameErr = $emailErr = $subjectErr = $commentsErr = $websiteErr = $findoptionErr = "";
//Initialize variable used to identify form is valid OR not.
$formValid = true;
//Check to see if the form was submitted.
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check the 'First Name' field.
if (empty($_POST["fname"]))
{
$formValid = false;//Form not validate
$fnameErr = "First Name is Required.";
}
else
{
$fname = validate_info($_POST["fname"]);
}
//Check the 'Last Name' field.
if (empty($_POST["lname"]))
{
$formValid = false;//Form not validate
$lnameErr = "Last Name is Required.";
}
else
{
$lname = validate_info($_POST["lname"]);
}
//Check the 'E-Mail' field.
if (empty($_POST["email"]))
{
$formValid = false;//Form not validate
$emailErr = "E-Mail is Required.";
}
else
{
$email = validate_info($_POST["email"]);
//Check if valid email.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$formValid = false;//Form not validate
$emailErr = "Invalid E-Mail Format.";
}
}
//Check the 'Subject' field.
if (empty($_POST["subject"]))
{
$formValid = false;//Form not validate
$subjectErr = "Subject is Required.";
}
else
{
$subject = validate_info($_POST["subject"]);
}
//Check the 'Website' field.
if (empty($_POST["siteurl"]))
{
$website = "";
}
else
{
$website = validate_info($_POST["siteurl"]);
//Check if valid URL.
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website))
{
$formValid = false;//Form not validate
$websiteErr = "Invalid URL.";
}
}
//Check the 'How Did You Find Us' options.
if (empty($_POST["howfind"]))
{
$formValid = false;//Form not validate
$findoptionErr = "Please Pick One.";
}
else
{
$findoption = validate_info($_POST["howfind"]);
}
//Check the comment box.
if (empty($_POST["questioncomments"]))
{
$formValid = false;//Form not validate
$commentsErr = "Questions/Comments are Required.";
}
else
{
$comments = validate_info($_POST["questioncomments"]);
}
//Pass any un-required data.
$likedsite = validate_info($_POST["likedsite"]);
}
//If every variable value set, send mail OR display error...
if (!$formValid){
echo"Form not validate...";
}
else {
//Make the message.
$message =
"
First Name: $fname.\n
Last Name: $lname.\n
Website: $website\n
Did They Like the Site? $likedsite.\n
How They Found Us. $findoption.\n
Question/Comments:\n
$comments.
";
$message = wordwrap($message, 70);
$headers = "From: $email";
mail("me#gmail.com", $subject, $message, $headers);
if($sendMail){
echo "Mail Sent!!";
}
else {
echo "Mail Not Sent!!";
}
}
function validate_info($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I edit my answer as per some change. Now this code only allow send mail if form required fields are not empty and all fields value are valid as per your validation.
Let me know if there is any concern.!
from what i was able to conceive, u are
trying to apply 'OR' in if condition- should be changed to AND i.e. change || to &&
you are checking for not empty error variables... which should be changed to verify if they all are empty or not.
if (empty($fnameErr) && empty($lnameErr) && empty($subjectErr) && empty($emailErr) && empty($commentErr) && empty($websiteErr) && empty($findoptionErr))
{
echo "sent";
}
Instead of writing lengthy conditions.
Assign all error messages to a single variable and append errors to it ($errorMsg). You can avoid lengthy if else ladder by doing this.
Change empty($_POST["email"]) to !isset($_POST["email"]) - In all statements.
Then update the condition to following,
<?php
if($errorMsg == ''){
//Make the message.
$message ="
First Name: ".$fname.".\n
Last Name: ".$lname."\n
Website: ".$website."\n
Did They Like the Site? ".$likedsite."\n
How They Found Us. ".$findoption."\n
Question/Comments:\n
".$comments." ";
$message = wordwrap($message, 70);
$headers = "From: $email";
mail("me#gmail.com", $subject, $message, $headers);
}else{
// Show $errorMsg
}
?>
Make it simple, I hope this helps.
I have a form, php validation, and send to email. My php validation works fine. My send to email works fine. When I use them both together, they work fine until I add header('Location: http://google.com'); exit(); I am using google.com for because I havent made my confirmation page yet. When I add this line to the php, that's when it goes straight to google.com when I go to my website. Can someone please help? I have been trying to figure out all of this validation and form to email for 2 straight days now, and I cannot figure it out. I know nothing about php. My code is below.
My php:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if ( ! preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if ( ! preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["email2"])) {
$email2Err = "It is required to re-enter your email.";
} else {
$email2 = test_input($_POST["email2"]);
// check if e-mail address syntax is valid
if ( ! preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email2)) {
$email2Err = "Invalid email format";
}
}
if (empty($_POST["comments"])) {
$commentsErr = "A comment is required.";
} else {
$comments = test_input($_POST["comments"]);
if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
// Everything ok. Do nothing and continue
} else {
$commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";
}
}
if (isset($_POST['service'])) {
foreach ($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
}
}
if (empty($errors)) {
$from = "From: Our Site!";
$to = "jasonriseden#yahoo.com";
$subject = "Mr Green Website | Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Comments: " . $comments . "";
mail($to, $subject, $message, $from);
header('Location: http://google.com');
exit();
}
?>
Please someone help me. I have no idea what is wrong.
Ok. I did what you told me Barmar. Not sure if I did it right or not. It solved one problem, but another was created.
I started over with the code that validates and sends the form data to my email. Now I just want to add header('Location: http://google.com '); exit(); ....and it work. Can you tell me what to do? I have no idea what php, so the more specific that you can be, the better.
Here is the php:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["email2"]))
{$email2Err = "It is required to re-enter your email.";}
else
{$email2 = test_input($_POST["email2"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email2))
{
$email2Err = "Invalid email format";
}
}
if (empty($_POST["comments"]))
{$commentsErr = "A comment is required.";}
else
{$comments = test_input($_POST["comments"]);
if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
// Everything ok. Do nothing and continue
} else {
$commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";
}
}
if (isset($_POST['service']))
{
foreach ($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($errors)) {
$from = "From: Our Site!"; //Site name
// Change this to your email address you want to form sent to
$to = "jasonriseden#yahoo.com";
$subject = "Mr Green Website | Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Comments: " . $comments . "";
mail($to,$subject,$message,$from);
}
?>
The problem is that there's no variable $errors. So if(empty($errors)) is always true, so it goes into the block that sends email and redirects. This happens even if the user hasn't submitted the form yet -- I'm assuming this code is part of the same script that displays the registration form after the code you posted.
You need to make two changes:
The code that sends the email and redirects should be moved inside the first if block, after all the validation checks.
Instead of if(empty($error)), it should check if($nameErr && $emailErr && $email2Err && $commentsErr). Or you should change the validation code to set $error whenever it's setting one of these other error message variables.
I know this isn't a direct answer to your question, but have a look into Exceptions. By having seperate functions for each validation and have them throw an exception when something is wrong, your code will be much cleaner and bugs will have much less room to pop up. Bonus points if you put all the validation functions in a class.
Example: (I renamed test_input() to sanitize_input(), because that's what it does)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try
{
$name = getValidatedName();
$email = getValidatedEmail();
// send email with $name and $email
}
catch (Exception $e)
{
echo '<div class="error">' . $e->getMessage() . '</div>';
}
}
function getValidatedName()
{
if (empty($_POST["name"]))
throw new Exception("Name is required");
$name = sanitize_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/", $name))
throw new Exception("Only letters and white space allowed");
return $name;
}
function getValidatedEmail()
{
if (empty($_POST["email"]))
throw new Exception("Email is required");
$email = sanitize_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // you don't have to reinvent the wheel ;)
throw new Exception("Invalid email format");
return $email;
}