I'm building a website and have I a php contact form.
Validation of the form and mail() function is working perfectly.
My php file for the form is handler.php.
Now to the problem. When I press the submit button and a error message is coming up, they comes up in a new blank page and that page is the same URL but it added /handler.php in the URL.
What i want to do is make the error messages show up under the form, and if it is no errors I want it to go to my thankyoumessage.html.
This is the php code for the form:
<?php
/*Set the mail of the reciever*/
$myemail = "mymail#example.com";
/*Display error message*/
function show_error($myError)
{
?>
<html>
<body>
<b>Var snäll och rätta till följande fel:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
/* Check inputs */
function check_input($data, $problem='error')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
// if ($problem && strlen($data) == 0)
// {
// show_error($problem);
// }
return $data;
}
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message']))
{
/* Check all form inputs using check_input function */
$name = check_input(utf8_decode($_POST['name']));
$subject = check_input(utf8_decode($_POST['subject']));
$email = check_input(utf8_decode($_POST['email']));
$message = check_input(utf8_decode($_POST['message']));
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Email adressen är inte giltig...");
echo "<script type='text/javascript'>alert('$message');</script>";
}
/*If name is empty show error message */
if (empty($_POST['name']))
{
show_error("Du måste skriva in ditt namn...");
}
/*If email is empty show error message */
if (empty($_POST['email']))
{
show_error("Du måste skriva in din email...");
}
/*If message is empty show error message */
if (empty($_POST['message']))
{
show_error("Ett meddelande krävs om du önskar att få hjälp av oss...");
}
/* Prepare the message for the e-mail */
$mail =utf8_decode("
Hej!
Ditt kontakt formulär har blivit besvarat av:
Namn: $name
E-mail: $email
Kundens meddelande:
$message
Meddelande slut.
");
echo "Tack för du kontaktar oss! \n Vi återkommer med ett svar så snart som möjligt!";
/* Send the message using mail() function */
mail($myemail, $subject, $mail);
}
else
{
?><span><?php echo "Fyll i alla fälten...";?></span> <?php
}
?>
And this is the Html to the form:
<form class="mt-5 ml-5 mr-5" method="POST" action="handler.php" id="reused_form">
<p id="contactForm" class="h4 text-center mt-5"><strong>Kontakta oss</strong></p>
<!-- input text(Name) -->
<div class="md-form">
<i class="fa fa-user prefix">*</i>
<input type="text" name="name" id="name" class="form-control">
<label>Ditt namn</label>
</div>
<!-- input email -->
<div class="md-form mt-5">
<i class="fa fa-envelope prefix">*</i>
<input type="email" id="name" name="email" id="email" class="form-control validate">
<label data-error="Fel" data-success="Rätt">Din email</label>
</div>
<div class="md-form mt-5">
<i class="fa fa-user prefix"></i>
<input type="text" id="subject" name="subject" class="form-control">
<label>Ämne</label>
</div>
<!-- input message -->
<div class="md-form mt-5">
<i class="fa fa-pencil prefix">*</i>
<textarea type="text" name="message" id="message" maxlength="5000" class="form-control md-textarea" rows="3"></textarea>
<label>Meddelande</label>
</div>
<div class="text-center mt-4 mb-4">
<button class="btn danger-color" name="submit" type="submit">Skicka</button>
</div>
</form>
If you don't want to use AJAX, You can just let the mail() function process the form in the same page as the following :
<?php
// we declare empty error variables
$error = $error_email = $error_name = $error_subject = $error_message = "";
if (isset($_POST['submit']))
{
/* Check all form inputs using check_input function */
$name = check_input(utf8_decode($_POST['name']));
$subject = check_input(utf8_decode($_POST['subject']));
$email = check_input(utf8_decode($_POST['email']));
$message = check_input(utf8_decode($_POST['message']));
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$error_email = "Email adressen är inte giltig...";
}
/*If name is empty show error message */
if (empty($_POST['name']))
{
$error_name = "Du måste skriva in ditt namn...";
}
/*If email is empty show error message */
if (empty($_POST['email']))
{
$error_email = "Du måste skriva in din email...";
}
/*If message is empty show error message */
if (empty($_POST['message']))
{
$error_message = "Ett meddelande krävs om du önskar att få hjälp av oss...";
}
/// You can add the subject validations here as well
if (empty($_POST['subject']))
{
$error_subject = "Ett meddelande krävs om du önskar att få hjälp av oss...";
}
/* Prepare the message for the e-mail */
$mail =utf8_decode("
Hej!
Ditt kontakt formulär har blivit besvarat av:
Namn: $name
E-mail: $email
Kundens meddelande:
$message
Meddelande slut.
");
if(mail($myemail, $subject, $mail))
{
/// We redirect to the thank you mesage uppon a successful message sending
header("Location:thankyoumessage.html");
}
else
{
// Failure message if the mail() function failed to trigger
$error = "Something wrong !";
}
}
?>
<form class="mt-5 ml-5 mr-5" method="POST" action="" id="reused_form">
<p id="contactForm" class="h4 text-center mt-5"><strong>Kontakta oss</strong></p>
<!-- input text(Name) -->
<div class="md-form">
<i class="fa fa-user prefix">*</i>
<input type="text" name="name" id="name" class="form-control" required >
<label>Ditt namn</label>
</div>
<!-- Error name -->
<div class="text-center mt-4 mb-4">
<?php echo $error_name;?>
</div>
<!-- input email -->
<div class="md-form mt-5">
<i class="fa fa-envelope prefix">*</i>
<input type="email" id="name" name="email" id="email" class="form-control validate" required>
<label data-error="Fel" data-success="Rätt">Din email</label>
</div>
<!-- Error email -->
<div class="text-center mt-4 mb-4">
<?php echo $error_email;?>
</div>
<div class="md-form mt-5">
<i class="fa fa-user prefix"></i>
<input type="text" id="subject" name="subject" class="form-control" required>
<label>Ämne</label>
</div>
<!-- Error subject -->
<div class="text-center mt-4 mb-4">
<?php echo $error_subject;?>
</div>
<!-- input message -->
<div class="md-form mt-5">
<i class="fa fa-pencil prefix">*</i>
<textarea type="text" name="message" id="message" maxlength="5000" class="form-control md-textarea" rows="3" required></textarea>
<label>Meddelande</label>
</div>
<!-- Error message -->
<div class="text-center mt-4 mb-4">
<?php echo $error_message;?>
</div>
<div class="text-center mt-4 mb-4">
<?php echo $error;?>
</div>
<div class="text-center mt-4 mb-4">
<button class="btn danger-color" name="submit" type="submit">Skicka</button>
</div>
</form>
It sounds like you need this in a single page, but your form is directing to a second page (handler.php). You might benefit from having all of the functionality in a single script that loads both the form and handles form submission. The algorithm might go something like this:
$showForm = $showThankYou = false;
$errorMessage = '';
//if form submitted
//check for errors
//if no errors
$showThankYou = true;
//else set error vars appropriately
$errorMessage = '...';
$showForm = true;
// else
$showForm = true;
From this point, you can include both your form and your thank you wrapped in conditionals. You can include your error message in your form html, as it will be blank when the form is first loaded.
if($showForm) {
// form code block
}
if($showThankYou) {
// thank you page
}
It is going to /handler.php because is set on the form action:
<form class="mt-5 ml-5 mr-5" method="POST" action="handler.php" id="reused_form">
If you want to stay on the same page after form submits, you have to leave action empty. Instead, you have to set a conditional that checks if submit is set:
if(isset($_POST['submit']){
include('handler.php');
}
Adding that code below your form will execute the script when the user hits submit (you have to modify it, it has to be an not a button).
That's one way to do it using exclusively PHP. You also can put all the code of sending mail inside a function, and execute it when submit is send:
function sendMail(){
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message']))
{
/* Check all form inputs using check_input function */
$name = check_input(utf8_decode($_POST['name']));
$subject = check_input(utf8_decode($_POST['subject']));
$email = check_input(utf8_decode($_POST['email']));
$message = check_input(utf8_decode($_POST['message']));
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Email adressen är inte giltig...");
echo "<script type='text/javascript'>alert('$message');</script>";
}
/*If name is empty show error message */
if (empty($_POST['name']))
{
show_error("Du måste skriva in ditt namn...");
}
/*If email is empty show error message */
if (empty($_POST['email']))
{
show_error("Du måste skriva in din email...");
}
/*If message is empty show error message */
if (empty($_POST['message']))
{
show_error("Ett meddelande krävs om du önskar att få hjälp av oss...");
}
/* Prepare the message for the e-mail */
$mail =utf8_decode("
Hej!
Ditt kontakt formulär har blivit besvarat av:
Namn: $name
E-mail: $email
Kundens meddelande:
$message
Meddelande slut.
");
echo "Tack för du kontaktar oss! \n Vi återkommer med ett svar så snart som möjligt!";
/* Send the message using mail() function */
mail($myemail, $subject, $mail);
}
else
{
?><span><?php echo "Fyll i alla fälten...";?></span> <?php
}
}
Changing the submit code
<?php
include('handler.php');
if(isset($_POST['submit'])){
sendMail();
}
?>
There are any other ways, but this two maybe solve your problem in a way that only uses PHP.
Hope it helps.
PD: You have the same ID for the name and email input.
Sounds like you need JavaScript, since the user will never leave the page. If you make handler.php return some json instead of a page, this will be super easy. First of all, I would put all your HTML in a file called contact.html so you can reference a different page from the one you're currently on. If you add an empty <p class="errorMsg"></p> to the body wherever you want, it will be invisible until there's an error.
Then you can add the below scripts in a file called submitForm.js, adding <script src="submitForm.js"></script> to the head of contact.html.
const formElement = document.querySelector('form')
const formData = new FormData(formElement)
formElement.onsubmit = event => {
event.preventDefault()
fetch('/handler.php', { method: 'POST', body: formData })
.then(response => response.json())
.then(json => {
const errorElement = document.querySelector('errorMsg')
errorElement.textContent = json.errorMsg
if (json.errorMsg !== '') document.location = '/thankyoumessage.html'
})
}
To break it down, fetch is a really easy way to make an ajax request. Your user will stay on the current page, but your code will go out to the URL and get its data for use on the current page. fetch() makes the request, and then() handles it synchronously after it gets the response. Here, I'm chaining two then()s because I need to parse it into json before I can access that data. The last then() is how you would handle the form submission.
Learn more about fetch
Fetch is a new web API that relies on ES6 features and may not be compatible with older browsers. I still encourage you to use it, because even if IE11 support is necessary, all it takes is a polyfill and a syntax converter to do all the work for you.
Now, to make fetch work like this, you'll need to put something in handler.php. You can use all the code in your first snippet, leaving out the HTML. You can return JSON just by building a string and echoing it, no html necessary. You could accomplish that by changing your show_error() function calls to assigning an $errorMsg variable, like this.
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$errorMsg = "Email adressen är inte giltig...";
}
then at the end of the file, instead of HTML you can write the JSON string like so.
echo '{ "errorMsg" : "' . $errorMsg . '" }';
Now, if your form still hit that page with an Email error for example, you would see this:
{ "errorMsg" : "Email adressen är inte giltig..." }
... Obviously you don't want to see that, but your JavaScript can see that without your user looking at it, and the JavaScript knows exactly what to do with that data, like we saw above. Then you can add as many things as you want to that JSON, so your live JavaScript can do other things with it.
Learn more about JSON
Related
I have this PHP form validator that is also hooked up to a mail function and to keep things organized I did the form validation in a separate function that is being called when the form is submitted.
Now I have this problem that I don't know how to display the error message when a field is empty in the HTML form.
Can anyone help? Thank you in advance.
I'm also pretty new to PHP and the whole thing.
PHP:
<?php
// Validation function
function validation($name, $email, $message) {
// Searching for every empty POST variable
// And if empty push into $error array
if (empty($name)) {
array_push($errors, "Name");
}
if (empty($email)) {
array_push($errors, "E-Mail");
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mail_error = " and E-Mail must be correct/filled out.";
}
if (empty($message)) {
array_push($errors, "Message");
}
// Combining all index of array to one final string
$final = implode(", ", $errors);
// Adding additional string to final
$final .= " is not allowed to be empty." . $mail_error . "\n";
return $final;
}
if (isset($_POST["submit"])) {
// Defining POST variables for validation and mail content
$fname = $_POST["fname"];
$femail = $_POST["femail"];
$fmessage = $_POST["fmessage"];
// Defining variable for pushing errors for validation
$errors = array();
// Calling function
validation($fname, $femail, $fmessage);
}
HTML:
<form name="main-form" action="" method="post" class="row g-3 pt-1 p-5 bg-custom">
<div class="input-group mb-3 col-md-6">
<span class="input-group-text">Name</span>
<input name="fname" type="text" class="form-control me-3 " placeholder="Name" aria-label="Name">
<span class="input-group-text">E-Mail</span>
<input name="femail" type="email" class="form-control" placeholder="example#mail.com"aria-label="example#mail.com">
</div>
<div class="input-group mb-3 col-md-12 col-sm-6">
<span class="input-group-text">Message</span>
<textarea name="fmessage" type="text" class="form-control"></textarea>
</div>
<!-- The error message if a field is empty should be displayed here: -->
<p id="error-message" class="text-center text-danger"><?php echo($final); ?></p>
<div class="col-md-12 text-center">
<button class="btn btn-primary me-2" id="btn-send" style="width: 30%;" class="btn btn-primary me-2" type="submit" name="submit">Send</button>
</div>
</form>
<?php
// Validation function
function validation($name, $email, $message) {
$errors = [];
$final = "";
// Searching for every empty POST variable
// And if empty push into $error array
if (empty($name)) {
array_push($errors, "Name");
}
if (empty($email)) {
array_push($errors, "E-Mail");
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mail_error = " and E-Mail must be correct/filled out.";
}
if (empty($message)) {
array_push($errors, "Message");
}
// Combining all index of array to one final string
$final = implode(", ", $errors);
// Adding additional string to final
$final .= " is not allowed to be empty." . $mail_error . "\n";
return $final;
}
if (isset($_POST["submit"])) {
// Defining POST variables for validation and mail content
$fname = $_POST["fname"];
$femail = $_POST["femail"];
$fmessage = $_POST["fmessage"];
// Defining variable for pushing errors for validation
// Calling function
$error = validation($fname, $femail, $fmessage);
}
HTML
<form name="main-form" action="" method="post" class="row g-3 pt-1 p-5 bg-custom">
<div class="input-group mb-3 col-md-6">
<span class="input-group-text">Name</span>
<input name="fname" type="text" class="form-control me-3 " placeholder="Name" aria-label="Name">
<span class="input-group-text">E-Mail</span>
<input name="femail" type="email" class="form-control" placeholder="example#mail.com"aria-label="example#mail.com">
</div>
<div class="input-group mb-3 col-md-12 col-sm-6">
<span class="input-group-text">Message</span>
<textarea name="fmessage" type="text" class="form-control"></textarea>
</div>
<!-- The error message if a field is empty should be displayed here: -->
<p id="error-message" class="text-center text-danger"><?=if(isset($error)); $error : "";?></p>
<div class="col-md-12 text-center">
<button class="btn btn-primary me-2" id="btn-send" style="width: 30%;" class="btn btn-primary me-2" type="submit" name="submit">Send</button>
</div>
</form>
$error = validation($fname, $femail, $fmessage); store data in variable and
isset() use to check variable exist or not
I have a question: i need to create a POST method form with a textarea, where the user can copy-paste multiple email adressses and my form should be able to do something with each adress separately.
And i don't know how to tell to php to recognize each email adress separately from the POST value of the textarea and insert them into a table of my database for example.
so my code looks like that for the moment:
<?php
if($_POST) {
if(!empty($_POST['emails'])) {
$emails = explode(" ", $_POST['Emails']);
foreach($emails as $email) {
/* Do something with each adresses ( like inserting them into a
table in my database for example) */
}
}
}
?>
<html>
<form class="mx-auto" method="POST" id="invitations">
<div class="form-group w-50 mx-auto text-center">
<label for="emails">Insert the email adresses</label>
<textarea name="emails" id="emails"></textarea>
<button id="send-data" class="btn btn-primary mx-auto my-5 text-center">Send the invitations</button>
</div>
</form>
</html>
<?php
if(!empty($_POST['Emails'])) {
$emails = explode(" ", $_POST['Emails']);
foreach($emails as $email) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Do something
} else {
echo "This email adress is not valid => $email !";
return;
/* here if something else than a space or a valid email adress is inserted
the foreach will be exited and a error message specifying where
something was wrong is displayed :) */
}
}
} else {
$feedback = "Please insert one or multiple email adress(es)";
}
if(isset($feedback) and !empty($feedback)) {
echo $feedback;
}
?>
<html>
<form class="mx-auto" method="POST" id="invitations">
<div class="form-group w-50 mx-auto text-center">
<label for="emails">Insert the email adresses</label>
<small>Separate them with a space</small>
<textarea name="emails" id="emails"></textarea>
<button id="send-data" class="btn btn-primary mx-auto my-5 text-center">Send the invitations</button>
</div>
</form>
</html>
I'm learning coding and created a simple form where error messages are
displayed just below each input field. However, when I check the form
the success message appears at the same time as error messages instead
of displaying when all the fields are correctly entered and form
validated. Can you please help. Thank yo in advance. Here is my
code.
</php>
$errorMessage = "";
$successMessage = "";
$emailError = "";
$emailconfirmError = "";
$nameError = "";
$messageError = "";
$servicesError = "";
$name = $email = $emailConfirm = $services = $message = "";
$email = isset($_POST['email']) ? $_POST['email'] : '';
$emailConfirm = isset($_POST['emailConfirm']) ? $_POST['emailConfirm'] : '';
if ($_POST) {
if (!$_POST['email']) {
$emailError .="The email is required";
}
if (!$_POST['emailConfirm']) {
$emailconfirmError .="Please confirm your email <br>";
}
if ($_POST['emailConfirm'] && $email != $emailConfirm) {
$emailconfirmError .="The email addresses do not match <br>";
}
if (!$_POST['name']) {
$nameError .="The name field is required <br>";
}
if (!$_POST['services']) {
$servicesError .="Please select a service required <br>";
}
if (!$_POST['message']) {
$messageError .="The message field is required <br>";
}
if ($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$emailError .= "The email address is invalid.<br>";
}
if ($name = $email = $emailConfirm = $services = $message != "") {
echo $emailError;
echo $emailconfirmError;
echo $name;
echo $services;
echo $message;
}else {
$emailTo = "kamala_guliyeva#hotmail.com";
$services = $_POST['services'];
$message = $_POST['message'];
$headers = "From: ".$_POST['email'];
if (mail($emailTo, $services, $message, $headers)) {
$successMessage = '<div class="alert alert-success" role="alert">Thank you for your message. We\'ll get back to you ASAP!</div>';
} else {
$errorMessage = '<div class="alert alert-danger" role="alert"><p>Your message couldn\'t be sent - please try again</div>';
}
}
}
and HTML
<div id="quote">
<div class="container">
<h2 class="section-title">Request a Quote</h2>
<hr align="left" width="8%" class="style-one">
<br>
<div><? echo $errorMessage.$successMessage; ?></div>
<form id="quoteForm" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="email" name="email" placeholder="Your email">
<label class="error" id="emailError"><?php echo $emailError; ?></label>
</div>
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="emailConfirm" name="emailConfirm" placeholder="Re-type your email">
<label class="error" for="e-mailConfirm" id="emailconfirmError"><?php echo $emailconfirmError; ?></label>
</div>
<div class="form-group">
<input type="name" class="form-control" id="name" style="height:60px" name="name" placeholder="Your Name">
<label class="error" for="name" id="nameError"><?php echo $nameError; ?></label>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<select class="form-control" id="services" name="services" style="height:60px">
<option value="">Select Services</option>
<option value="Installation">Installation</option>
<option value="Repair">Repair</option>
<option value="Service and Maintenance">Service and Maintenance</option>
</select>
<label class="error" for="services" id="servicesError"><?php echo $servicesError; ?></label>
</div>
<div class="form-group">
<textarea class="form-control" id="message" name="message" placeholder="Message" style="height: 163px;" cols="35"></textarea>
<label class="error" for="message" id="messageError"><?php echo $messageError; ?></label>
</div>
</div>
</div>
<div class="form-row text-center">
<div class="col-12">
<button type="submit" style="width:10rem" class="btn quoteButton pt-3 pb-3 text-align-center">Get a Quote</button>
</div>
</div>
</form>
</div>
</div>
You've a few problems there...
So first thing is how you are doing your checks.
if(!$_POST) {
is not a valid way of checking that a post has occurred you need to do something like
if(isset($_POST) && !empty($_POST)) {
would be more appropriate as you are checking if the POST array is actually set and then that it is not empty the && operator is a short circuit operator so if either condition isn't met then the check will fail.
Similarly on your comparisons saying if(!$_POST['email']) { isn't valid because you're effectively asking "if the email part of the post array is not true" where as you need to be asking "if it's not blank and is a valid email address"
You need to be aware of the difference between = == and === operators. You can find some more information here: The 3 different equals
And also the filter_var function here: http://php.net/manual/en/function.filter-var.php
if($_POST['email']!=="" && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
//all good
} else {
//set your error message
}
you can use regular expressions to validate 'name' see preg_match in the manual http://php.net/manual/en/function.preg-match.php
Aside from all of this if you want to have real time monitoring of the fields and the error messages etc you're going to have to look at incorporating Javascript and using AJAX to communicate with your script and then parse the response back into the appropriate div.
Have a look at Rasmus 30 second AJAX tutorial will give you a starting point for this http://rajshekhar.net/blog/archives/85-Rasmus-30-second-AJAX-Tutorial.html
However it is better practice to do both client and server side validation hope this helps even if it is not a complete answer per sé.
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
PHP form validation not working, allowing invalid submissions to be sent
Closed 4 years ago.
So I have asked a similar question but in the comments, I was told a possible answer however it didn't work so I'm posting another one. The situation is slightly different so I didn't know whether to edit and update the other one or make a new one.
Anyway, I have a form and a PHP script that is supposed to validate the form data when the user submits and for now(testing purposes) if it does not pass the validation an array with strings should print.
Berfore I go on here is the html:
<form method="post" action="mail3.php" class="col-12" id="form-book">
<div class="row">
<div class=" form-group col-12">
<p>Fill out the form below to tell me about your problem. <strong>Any problems to do with technology, all the solutions.</strong> Just tell me what you can, however the more info you give the better.</p>
</div>
<div class="form-group col-6">
<label></label>
<input id="name" name="name" placeholder="Name" type="text" required="required" class="form-control here bottom"> <span class="error">
</div>
<div class="form-group col-6">
<label></label>
<input id="phone" name="phone" placeholder="Phone#" type="text" required="required" class="form-control here bottom"> <span class="error">
</div>
<div class="form-group col-12">
<label></label>
<input id="email" name="email" placeholder="Email (Optional)" type="text" class="form-control here bottom"> <span class="error">
</div>
<div class="form-group col-6">
<input data-provide="datepicker" id="date" name="date" placeholder="Pick a date" required="required" class="form-control here bottom">
</div>
<div class="form-group col-6">
<input type="text" id="time" name="time" placeholder="Choose the best time" required="required" class="form-control here bottom timepicker">
</div>
<div class="form-group col-12">
<label></label>
<textarea id="message" name="message" cols="40" rows="5" class="form-control" required="required" aria-describedby="messageHelpBlock"></textarea>
<span id="messageHelpBlock" class="form-text text-muted">Tell me a little about whats going on or what you need help with.</span>
</div>
<div class="form-group col-12">
<button name="submit" type="submit" class="btn btn-primary">Send your message</button>
</div>
</div>
<!--row-->
</form>
PHP:
<?php
date_default_timezone_set("Pacific/Honolulu"); //set the DateTimeZone
function test_input($data) { //test input func that checks data
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$date = $_POST['date'];
$time = $_POST['time'];
$message = $_POST['message'];
$subject = "Appointment Booked";
$email = filter_var($email, FILTER_SANITIZE_EMAIL); //clean email
$mailTo = "itguy#johnpuaoi.com";
$dateTested = test_input($date);
$timeTested = test_input($time);
$errors = []; //set errors arrray
//funcs will check each input and if an error is detected it will add a string to errors array
//if no errors are found the input is then passed into xTested variable
function validateName($input) {
if (empty($input)) { //check if empty
return $errors[] = "Your name is required."; //if empty add string to errors array
} elseif (is_int($input)) { //check if input is an interger
return $errors[] = "That is not a valid name."; //if is interger add string to errors array
} else {
return $nameTested = test_input($input); //return tested input variable
}
}
function validatePhone($input) {
if (empty($input)) { //check if empty
return $errors[] = "Your phone number is required."; //add string to array if empty
} elseif (!preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $input)) { //check if input does not match
return $errors[] = "That is not a valid name."; //add string to array if no match
} else {
return $phoneTested = test_input($input); //return tested input variable
}
}
function validateEmail($input) {
if (empty($input)) { //check if empty
return $errors[] = "Your email is required.";//add string to array if empty
} elseif (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return $errors[] = "That is not a valid email.";
} else {
return $emailTested = test_input($input); //return tested input variable
}
}
function validateMessage($input) {
if (empty($input)) { //check if empty
return $errors[] = "Your message can't be empty.";//add string to array if empty
} else {
return $messageTested = test_input($input); //return tested input variable
}
}
validateName($name); //call validate funcs
validatePhone($phone);
validateEmail($email);
validateMessage($message);
$headers = "From: ".$emailTested;
$txt = "An appointment was booked by ".$nameTested.".\n\n".$dateTested." #".$timeTested.".\n\n".$messageTested;
if ($errors == null) { //if errors array is empty
mail($mailTo, $subject, $txt, $headers); //mail data
header("Location: index.php?mailsend"); //redirect to home
} else {
print $errors; //print errors to test if validate funcs work
}
}
?>
Now I have created validate functions for a set data type - name, email, phone and message. It checks the input and if an error occurs then a string is added to the errors array. If no error is found then the input is passed to a variable to tells php it has been tested for errors.
IMPORTANT In the last question I asked, in the comments someone pointed out that I did not have anything stopping the mail func even if the data did not pass validation. So to fix that I included an if statement at the bottom that checks if the errors array is empty. If it is then the mail func is called, if it isn't then for testing purposes the errors array is printed.
I test the script by purposely entering invalid data but the form submits anyway. What is allowing the script to still mail the form data?
Now if you could not tell already, I am new to php so forgive me if I its something simple. I apologize in advance also if I should have just edited the first question.
This code works fine in seperated file named form.php, but when i paste it to
wordpress theme page it does not even validate form and not even send mail of course. Why is there no any action after i clikced submit button in wordpress theme?
Anyone can help me to solve problem?
get_header();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$nameError = $mailError = $messageError = '';
function validate($data){
if(empty($data)){
return false;
}else{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
//Validate name input
if(!validate($_POST['name'])){
$nameError = 'Polje ime je obavezno.';
}else{
if (!preg_match("/^[a-zA-Z ]*$/",$_POST['name'])) {
$nameError = "Polje moze sadrzavati samo slova i razmak";
}
}
//Validate email input
if(!validate($_POST['email'])){
$mailError = 'Polje email je obavezno';
}else{
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$mailError = "Nevazeća email adresa";
}
}
//Validate message textarea
if(!validate($_POST['message'])){
$messageError = 'Molimo unesite poruku';
}
if(empty($nameError) && empty($mailError) && empty($messageError)){
//Create the body
$body = "Ime: {$_POST['name']}\n\nPoruka: {$_POST['message']}";
//Make it no longer than 70 characters long
$body = wordwrap($body, 70);
//Send the mail
mail('example#example.com', 'Contact Form Submission',
$body,
"From: {$_POST['email']}");
//Print a message
echo '<p><em>Thank you for contacting me. I will reply some day.
</em></p>';
}else{
echo '<p style="font-weight: bold; color: #C00">Please fill out
the
form completley.</p>';
}
}
HTML Code that is placed in same file as php validation
<section class="contact-img">
<div class="container-fluid">
<div class="row">
<?php the_post_thumbnail(); ?>
</div>
</div>
</section>
<section class="contact">
<div class="container">
<div class="row">
<?php dynamic_sidebar('contact-page'); ?>
<div class="col-md-12">
<h4 class="col-xs-12 text-center"><strong>Ostavite
poruku</strong></h4>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-xs-10 col-xs-offset-1 col-sm-6 col-sm-offset-3">
<form method="POST" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<input type="text" class="form-control" name="name"
value="" placeholder="Ime">
<div><?php if(isset($nameError)) echo $nameError; ?>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="email"
value="" placeholder="E-mail">
<div><span class="error"><?php if(isset($mailError))
echo $mailError; ?></span></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="3"
placeholder="Poruka"></textarea>
<div><span class="error"><?php
if(isset($messageError)) echo $messageError; ?></span></div>
</div>
<input class="btn btn-default" type="button" name="button"
value="Pošalji">
</form>
</div>
</div>
</div>
</section>
You have a syntax error (white page of death, if error reporting is off)
$nameError = 'Polje moze sadrzavati samo slova i razmak;
Should be:
$nameError = 'Polje moze sadrzavati samo slova i razmak';
Another thing that might get you is your name validation Regex is to simple, it doesn't account for things like Jane Doe-Smith, or J o h n S m i t h or j or even '', an empty string.
I would use something like this:
if(!preg_match("/^([a-z]+)\s+(?:([a-z]+)\s+)?([-a-z]+)$/i" , $_POST['name'])){
$nameError = 'Polje moze sadrzavati samo slova i razmak;
}
Regex:
([a-z]+) matches a though z (first 2 capture groups)
\s+ matches one or more space
(?...) non-capture group ? optionally, middle name
([-a-z]+) matches - and a though z (for hyphenated last names)
\i case insensitive flag.
Regex Test
Test cases:
John Smith {match}
John E Smith {match}
Jane J Doe-Smith {match}
John {no match}
Which is still a small sample size, but should cover most English names ( not sure what language this is Polje moze).
I once dated a girl many many years ago with a hyphenated last name ... lol.
The last thing is to turn on display errors and set error reporting to a value like E_ALL (for development). I'd say use ini_set('display_errors', '1') and error_reporting() but they won't catch syntax errors in the same file (generally).