PHP Contact Form validation on submit - php

So the deal is this: the validation process starts after the user hits submit. However for some reason the code is not working.
PHP:
if ($_POST['submitted']) {
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
my_contact_form_generate_response("error", $email_invalid);
else //email is valid
{
//validate presence of name and message
if (empty($name) || empty($message)) {
my_contact_form_generate_response("error", $missing_content);
} else //ready to go!
{
$sent = wp_mail($to, $subject, strip_tags($message), $headers);
if ($sent) my_contact_form_generate_response("success", $message_sent); //message sent!
else my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
}
}
} else {
$response = "";
}
HTML:
<form action="<?php the_permalink(); ?>" class="contact" method="post">
<input type="text" placeholder="Your Name" name="message_name" value="<?php echo esc_attr($_POST['message_name']); ?>">
<input type="text" placeholder="Your Email" name="message_email" value="<?php echo esc_attr($_POST['message_email']); ?>">
<input type="text" placeholder="Your Company" name="message_company" value="<?php echo esc_attr($_POST['message_company']); ?>">
<textarea name="message_text" rows="10" placeholder="Your Message"><?php echo esc_textarea($_POST['message_text']); ?></textarea>
<button type="submit" class="contact-button" name="submitted">Submit</button>
</form>
<?php echo $response ?>
EDIT:
Sorry I forgot to add the last part of my post, what I ment was the PHP script should work the moment I hit the submit buttom. But the if ($_POST['submitted']) {} doesn't get triggered by my submit button. I was wondering why that is?

To me, it looks like you aren't assigning your variables to POST elements.
If you replace $email with $_POST['message_email'], $name with $_POST['message_name'], $message with $_POST['message_text'] in your first snippet you may find better luck.
Regardless, I can see quite a few unused variables in this snippet including $headers, $to, $subject, and every reporting variable used under my_contact_form_generate_*. Make sure these are also set.

Related

Wordpress custom form, loads wrong template after submit, doesn't send mail

Im trying to build a simple contact form for a Wordpress site. I want it to send an email and reload the contact page it was sent from with an error/success message.
I have installed WP mail SMTP and it sends the test email.
Now to the problems. I have a form in html that I want to use. This form has been put in a custom template.
The php is borrowed from guides I have found online and I have used several of them. None of them work for me. When I hit the submit button the page loads the base template (not the custom template that I'm using for the form page) and no mail is sent. I want it to load the same page but with an error/success div telling me what happened. If I run the php before pressing submit it gives me the error message.
Here is my php:
if(isset($_POST['submitButton'])){
//response generation function
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $reason){
global $response;
if($type == "success") $response = "<div class='success'>{$reason}</div>";
else $response = "<div class='error'>{$reason}</div>";
}
//response messages
$not_human = "Human verification incorrect.";
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//user posted variables
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$phone = $_POST['phone'];
$human = 2;
//php mailer variables
$to = get_option('admin_email');
$subject = "Someone sent a message from ".get_bloginfo('name');
$headers = 'From: '. $email . "\r\n" .
'Reply-To: ' . $email . "\r\n";
if(!$human == 0){
if($human != 2) my_contact_form_generate_response("error", $not_human); //not human!
else {
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
my_contact_form_generate_response("error", $email_invalid);
else //email is valid
{
//validate presence of name and message
if(empty($name) || empty($message)){
my_contact_form_generate_response("error", $missing_content);
}
else //ready to go!
{
$sent = mail($to, $subject, strip_tags($message),
$headers);
if($sent) my_contact_form_generate_response("success",
$message_sent); //message sent!
else my_contact_form_generate_response("error",
$message_unsent); //message wasn't sent
}
}
}
}
else if ($_POST['submitted'])
my_contact_form_generate_response("error", $missing_content);
}
?>
Here is my html for the "print error/success" and the form:
<?php echo $response; ?>
<form class="interest-form" action="<?php the_permalink(); ?>" method="POST">
<fieldset>
<legend>Anmäl Intresse:</legend>
<div class="row">
<div class="col-6">
<input type="text" class="form-control" placeholder="Namn" name="name" value="<?php echo esc_attr($_POST['name']); ?>">
</div>
<div class="col-6">
<input type="tel" class="form-control" placeholder="Telefonnummer" name="phone" value="<?php echo esc_attr($_POST['phone']); ?>">
</div>
</div>
<div class="row">
<div class="col">
<input type="email" class="form-control" placeholder="E-post" name="email" value="<?php echo esc_attr($_POST['email']); ?>">
</div>
<div class="col">
<input class="form-control" type="text" placeholder="<?php the_field('fb_8_1_plats'); ?> <?php the_field('fb_8_1_startdatum'); ?>" readonly name="plats_datum">
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="meddelande1">Meddelande:</label>
<textarea class="form-control" rows="3" name="message" value="<?php echo esc_attr($_POST['message']); ?>" id="meddelande1"></textarea>
</div>
</div>
</div>
<input type="hidden" name="submitted" value="1">
<button type="submit" name="submitButton" class="btn btn-primary float-right">Skicka intresseanmälan</button>
</fieldset>
</form>
I really can't figure out what is wrong, I spent two full days just googling, trying and failing last weekend. After that I gave up and haven't looked at at for a week. Please help!
Edit: It doesn't load index.php, the path is still the same but it uses the template for index.php

Include fields in message of PHP contact form

Being so bad at PHP, I've decided to post here as a last resort.
I want to add a "who" variable to the message body of emails sent via PHP contact form. The form works fine for name, email and message but the "who" input I would like to be a part of the email message that comes through, as a way to communicate who is being referred.
I have tried to add $who=$_REQUEST['who']; as well as $who to the mail line but neither work, the latter doesn't even send an email at all.
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
<input name="name" type="text" placeholder="Your Name" value="" size="14"/>
<input name="email" type="text" placeholder="Your Email" value="" size="14"/>
<textarea name="who" placeholder="Who should we contact?" rows="1" cols="14"></textarea>
<textarea name="message" placeholder="Description" rows="2" cols="14"></textarea><br>
<input type="submit" class="button special" value="SUBMIT"/>
</form>
<?php
}
else
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "All fields are required, please fill out the form again.";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Referral for ******* **";
mail("chris#********.com.au", $subject, $message, $from);
}
{
echo "<script type='text/javascript'>window.location.href ='../thanks.php';</script>";
}
}
?>
In PHP . is the concatenation operator which returns the concatenation of its right and left arguments
Try this
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'] . "\n\rFrom: " . $_REQUEST['who'];

PHP Form Message

So I have a form:
<form method="post" action="contactus.php?message=ok" name="myForm" autocomplete="off">
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name" maxlength="60" required/>
<label for="email">Email:</label>
<input type="text" name="email" id="email" maxlength="120" required/>
<label for="message">Message:</label><br />
<textarea name="message" rows="20" cols="20" id="message" required></textarea>
<input type="submit" name="submit" value="Submit" class="submit-button" onsubmit="displayMessage()" />
And the code to send the email:
<?php
if($_POST["submit"]) {
// The message
$message=$_POST["message"];
$email=$_POST["email"];
// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70, "\r\n");
// Send
mail('myemail.co.uk', $email, $message);
$sent_mail = true;
}
?>
And finally:
<?php
if (isset($sent_mail)) {
echo 'Thank you. We will be in touch soon.';
}
?>
So when the email is sent, sent_mail is set to 'true' and therefore the thank you message should be echoed. But right now this isn't working. The email sends first but the thank you message doesn't show. I basically just need a thank you message to come up somewhere on the page when the submit button is pressed.
Any ideas?
Instead of isset use simply if
Like this
<?php
if ($sent_mail) {
echo 'Thank you. We will be in touch soon.';
}
else
echo 'Unale to send message';
?>
mail function returns a boolean (true/false), so you can do like this
if (mail('myemail.co.uk', $email, $message)) {
echo "Thank you. We will be in touch soon.";
} else {
echo "Something went wrong, the email was not sent!";
}
Also, the structure of mail (the parameters) are to-address, subject, message. Which means that your current subject is the email-address, I'm not sure if this is what you intended?
Use
if(mail('myemail.co.uk', $email, $message))
$sent_mail = true;
else
$sent_mail = false;
And finally:
<?php
if ($sent_mail) {
echo 'Thank you. We will be in touch soon.';
}
else
echo 'Message cannot be send';
?>
You are assigning Boolean to $sent_mail and you set it to True.
<?php if($sent_mail){
echo "Email sent successfully";} ?>

Contact Form Disappearing When Div is Set?

Ok, so I've got a contact form:
<?php
if (isset($_POST['subtest'])) {
$to = 'thomofawsome#gmail.com';
$name = $_POST['firstname'];
$lastName = $_POST['lastname'];
$email = $_POST['email'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$comments = $_POST['comments'];
$Message = <<< STOP
From: $name $lastName
Email: $email
In: $city, $state, $zip
Comments: $comments
STOP;
$subject = "Contact Request";
$headers = 'From: system';
if (mail($to, $subject, $Message, $headers)) {
echo '<div id="thanks">Mail sent</div>';
exit();
}
else {
echo 'Mail Failed';
}
}
?>
<form name="contact_form" action="" method="post">
<input type="hidden" name="subtest" value="true">
First Name:<br>
<input type="text" name="firstname">
<br>
Last Name:<br>
<input type="text" name="lastname">
<br>
Email Address:<br>
<input type="text" name="email">
<br>
City:<br>
<input type="text" name="city">
<br>
State:<br>
<input type="text" name="state">
<br>
Zip:<br>
<input type="text" name="zip">
<br>
Comments:<br>
<textarea name="comments"></textarea>
<br>
<input id="submit" type="submit" name="submit" value="Send">
<br>
</form>
The problem is I want the echo mail sent correctly formatted (with a green color, positioned correctly on the page, etc.). As you can see, I've put it in a div. When I submit the form though, I'm redirected back to the form page, except the entire form and footer disappear, and Mail sent appears on the bottom of the page (correctly formatted).
Any ideas?
The exit() function prevents the rest of the script from executing, which includes your form and footer. Remove it and it will work.
if (mail($to, $subject, $Message, $headers)) {
echo '<div id="thanks">Mail sent</div>';
} else {
echo 'Mail Failed';
}
As Raidenance pointed out, if someone refreshes this page after posting the form it will resend the email address. A better solution to this problem is to post your contact form to another url (/contact/submit for instance) and on completion of the script execution at that url simply redirect back to the contact form with a parameter
header("Location:/contact?success=true");
Then on your contact form page:
if (isset($_GET['success']) && $_GET['success'] == "true") {
echo '<div id="thanks">Mail sent</div>';
} else {
echo 'Mail Failed';
}
This will prevent the issue of the user reloading and receiving the email multiple times.

HTML form disapearing after Error/Email is sent (PHP)

weird problem here, my html form disapears from the page when I click the send button regardless of success or not.
I display an alert box to indicate if the email was sent or not.
here is the code
<?php
$action = $_REQUEST['action'];
if ($action == "") /* display the contact form */ {
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
<input class="champTextFormulaire" placeholder="Votre Nom" name="name" type="text" value="" size="30"/><br>
<input class="champTextFormulaire" placeholder="Votre email" name="email" type="text" value="" size="30"/><br>
<textarea id="champMessage" placeholder="Votre Message..." name="message" rows="7" cols="30"></textarea><br>
<input class="btnEnvoiFormulaire" type="submit" value="Envoi"/>
</form>
<?php
} else /* send the submitted data */ {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
if (($name == "") || ($email == "") || ($message == "")) {
print '<script type="text/javascript">';
print 'alert("Veuillez remplir tout les champs")';
print '</script>';
} else {
$from = "From: $name<$email>\r\nReturn-path: $email";
$subject = "Message sent using your contact form";
mail(desiletsmathieu#gmail.com", $subject, $message, $from);
print '<script type="text/javascript">';
print 'alert("Mail envoyé")';
print '</script>';
}
}
}
?>
This is happening because you are using $_REQUEST['action']
After your are submitting the form, your hidden field action becomes $_REQUEST['action'];
And after you submit the form, you get $action = $_REQUEST['action']; to be submit.
Where as you should have a blank value for $_REQUEST['action'] to display the form.
Solution:
1) Either, modify if ($action == "submit")
2) Or, assign blank value to the action (hidden) field
Try it this way.
First off, you forgot a double quote just after mail( that read like this:
mail(desiletsmathieu#gmail.com", $subject, $message, $from);
and needed to be changed to:
mail("desiletsmathieu#gmail.com", $subject, $message, $from);
Plus enctype="multipart/form-data" is for file attachments/uploading so you don't need that.
I also removed this line, which was no longer required:
<input type="hidden" name="action" value="submit">
This works and tested:
Note: I added a name to your submit button in order to give it an extra condition. Plus, you basically had your conditions already set, it just needed to be reworked/rethinked and using less code to achieve the same result.
<form action="" method="POST">
<input class="champTextFormulaire" placeholder="Votre Nom" name="name" type="text" value="" size="30"/><br>
<input class="champTextFormulaire" placeholder="Votre email" name="email" type="text" value="" size="30"/><br>
<textarea id="champMessage" placeholder="Votre Message..." name="message" rows="7" cols="30"></textarea><br>
<input class="btnEnvoiFormulaire" type="submit" name="submit" value="Envoi"/>
</form>
<?php
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (isset($_POST['submit'])) {
if (($name=="")||($email=="")||($message==""))
{
print '<script type="text/javascript">';
print 'alert("Veuillez remplir tout les champs")';
print '</script>';
exit;
}
else
{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("desiletsmathieu#gmail.com", $subject, $message, $from);
print '<script type="text/javascript">';
print 'alert("Mail envoyé")';
print '</script>';
exit;
}
}
?>

Categories