Simple PHP Contact Form - 2 Days of Pain - php

I have no real experience with PHP, and so have just pulled bits of code from various answers to help construct a simple PHP contact form. I have spent two days trying to work out why various variations aren't working. I've included my code:
HTML :
<section class="form-section" id="form-section">
<div class="row headline">
<h3>Free Quotation</h3> </div>
<div class="row">
<form action="mailer.php" method="post" name="htmlform" class="contact-form" target="_blank">
<div class="col span-1-of-2">
<div class="row inputs">
<label for="name">Name</label>
<input name="name" placeholder="Your name" required="" type="text"> </div>
<div class="row inputs">
<label for="email">Email</label>
<input name="email" placeholder="Your email" required="" value="" type="email" class="required email"> </div>
<div class="row inputs">
<label for="business_name">Business Name</label>
<input value="" name="business_name" placeholder="Your business name" required="" type="text" class=""> </div>
</div>
<div class="col span-1-of-2 message-box-container">
<label class="text-box-label" for="message">In a few words, what are you looking for?</label>
<textarea name="message" placeholder="Your message"></textarea>
</div>
<div class="row form-messages">
<?php
if($_GET['success'] == 1) {
echo "<div class="success">Thank You! We'll aim to follow up as soon as possible</div>";
}
if($_GET['success'] == -1) {
echo "<div class="error">Oops something went wrong, please try again</div>";
}
?> </div>
<div class="col span-2-of-3">
<div class="clear">
<input type="submit" value="Find Out More" name="subscribe" class="button"> </div>
</div>
</form>
</div>
</section>
This is my mailer.php form:
<?php
// Get the form fields, removes html tags and whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$business_name = strip_tags(trim($_POST["business-name"]));
$business_name = str_replace(array("\r","\n"),array(" "," "),$business_name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check the data.
if (empty($name) empty($business_name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
// Set the recipient email address. Update this to YOUR desired email address.
$recipient = "chussell#thegreenbuddha.co.uk";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$email_content .= "Business Name: $business_name \n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
mail($recipient, $subject, $email_content, $email_headers);
// Redirect to the index.html page with success code
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=1#form");
?>
When I have this on live preview both success and error messages display with PHP code. I have the file saved as a index.php. And when I submit it opens up the fresh page which is blank.
When I've added the new index.php and mailer.php to my cpanel, my website no longer displays!
Any suggestions or improvements?
Many thanks!

The following
<?php
if($_GET['success'] == 1) {
echo "<div class="success">Thank You! We'll aim to follow up as soon as possible</div>";
}
if($_GET['success'] == -1) {
echo "<div class="error">Oops something went wrong, please try gain</div>";
}
?>
Into
<?php
if($_GET['success'] == 1) {
echo '<div class="success">Thank You! We\'ll aim to follow up as soon as possible</div>';
}
if($_GET['success'] == -1) {
echo '<div class="error">Oops something went wrong, please try gain</div>';
}
?>
The following
if (empty($name) empty($business_name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
Into
if (empty($name) || empty($business_name) || empty($message) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
Please change the following also:
$business_name = strip_tags(trim($_POST["business-name"]));
Into
$business_name = strip_tags(trim($_POST["business_name"]));

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

Php mail function sends email every time page is refreshed

I used the mail function to do a contact form and it all works fine. However, I just noticed that after sending an email, every time a refresh the page, even though the fields are empty, an email keeps being sent.
My code looks like this:
<form role="form" method="POST">
<br style="clear:both">
<h3 style="margin-bottom: 25px; text-align: center;">Contact a Conveyancing Property Lawyer Now</h3>
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="email" name="email" placeholder="Email" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Contact Number" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<select name="situation" id="situation">
<option>Select Current Situation</option>
<option class="placeholder" value="Unemployed">Unemployed</option>
<option class="placeholder" value="Employed">Employed</option>
</select>
</div>
<button type="submit" id="submit" name="submit" class="btn btn-primary">Submit</button>
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$subject_line = $_POST['subject'];
$situation = $_POST['situation'];
$from = 'myemail#email.co.za';
$to = 'myemail#email.co.za';
$subject = 'SchoemanLaw lead ...';
$body ="From: $name <br/> E-Mail: $email <br/> Mobile: $mobile Subject: $subject_line <br/> Situation: $situation";
//$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";
// set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers optional/headers
$headers .= "From:$from";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
// Check if mobile has been entered
if (!$_POST['mobile']) {
$errMobile = 'Please enter your number';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMobile) {
if (mail($to,$subject,$body,$headers)) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
echo $result;
}
}
}
?>
</form>
How can I make the site forget all the details from the input fields once an email is sent?
I tried to follow this question here but I don't seem to be able to make it work on my site
The easiest way is to add an forwarding in your code, like that:
EDIT: at #CD001 commentary
if (mail($to,$subject,$body,$headers)) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
// header('Location: ?successfull-submit'); exit; // this one would fail because above is an output.
echo '<meta http-equiv="refresh" content="0; url=?successfull-submit">'; // its not a good /nice alternative but it "works".
Redirect to ?sent=1 without sending any output. And check 'sent' to determine whether or not to display the success message. Try below (assuming your script is contact.php). Also make sure
contact.php
<?php
$result = '';
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$subject_line = $_POST['subject'];
$situation = $_POST['situation'];
$from = 'myemail#email.co.za';
$to = 'myemail#email.co.za';
$subject = 'SchoemanLaw lead ...';
$body ="From: $name <br/> E-Mail: $email <br/> Mobile: $mobile Subject: $subject_line <br/> Situation: $situation";
//$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";
// set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers optional/headers
$headers .= "From:$from";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
// Check if mobile has been entered
if (!$_POST['mobile']) {
$errMobile = 'Please enter your number';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMobile) {
if (mail($to,$subject,$body,$headers)) {
//$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
//echo $result;
header('Location:' . 'contact.php?sent=1');
exit;
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
//echo $result;
}
}
}
if(isset($_GET['sent'])) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
}
echo $result;
?>
<form role="form" method="POST">
<br style="clear:both">
<h3 style="margin-bottom: 25px; text-align: center;">Contact a Conveyancing Property Lawyer Now</h3>
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="email" name="email" placeholder="Email" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Contact Number" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<select name="situation" id="situation">
<option>Select Current Situation</option>
<option class="placeholder" value="Unemployed">Unemployed</option>
<option class="placeholder" value="Employed">Employed</option>
</select>
</div>
<button type="submit" id="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
try like this,in your success message part..
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$subject_line = $_POST['subject'];
$situation = $_POST['situation'];
$from = 'myemail#email.co.za';
$to = 'myemail#email.co.za';
$subject = 'SchoemanLaw lead ...';
$body ="From: $name <br/> E-Mail: $email <br/> Mobile: $mobile Subject: $subject_line <br/> Situation: $situation";
//$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";
// set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers optional/headers
$headers .= "From:$from";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
// Check if mobile has been entered
if (!$_POST['mobile']) {
$errMobile = 'Please enter your number';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMobile) {
if (mail($to,$subject,$body,$headers)) {
echo "<script>alert('Mail sent Successfully');</script>";
echo "<script>window.location = 'contact.php';</script>";
} else {
echo "<script>alert('Mail not sent');</script>";
echo "<script>window.location = 'contact.php';</script>";
}
}
}
?>
while redirect to another page you can restrict that duplication problem....
Just try redirecting to another page or another function that discards the old $_POST data.
You could use session variable and reset it after each request.
Or, prevent reloading same page using javascript.
Or, redirect to some other page upon completion (if possible)
You can try to add CSRF token to your page to prevent double submission.
Refer to this link: How to prevent multiple form submission on multiple clicks in PHP
When the user refreshes the page, it is possible that the same parameters are getting posted again. As a result, if (isset($_POST["submit"])) This condition becomes true and mail will be sent every time user reloads.
One solution is to redirect to the same page or to a different page on success full completion.
ie,
if (mail($to,$subject,$body,$headers)) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
}
Instead of the above method, redirect user to the same page or different page and show a message there. If you want to show the same page you can redirect with a flag in the query string as ?show_success_msg= true.
Then do this.
if(isset($_GET['show_success_msg']) && $_GET['show_success_msg'] == 'true') {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
}
Complete solution here:
<?php
// Handle PHP code always on Top of the page (ie, Not after your HTML), You cant send headers if you have any content above it.
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$subject_line = $_POST['subject'];
$situation = $_POST['situation'];
$from = 'myemail#email.co.za';
$to = 'myemail#email.co.za';
$subject = 'SchoemanLaw lead ...';
$body ="From: $name <br/> E-Mail: $email <br/> Mobile: $mobile Subject: $subject_line <br/> Situation: $situation";
//$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";
// set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers optional/headers
$headers .= "From:$from";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
// Check if mobile has been entered
if (!$_POST['mobile']) {
$errMobile = 'Please enter your number';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMobile) {
if (mail($to,$subject,$body,$headers)) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
} else {
header("Location: your_page.php?show_success_msg=true")
}
}
}
?>
<form role="form" method="POST">
<?php if(isset($_GET['show_success_msg']) && $_GET['show_success_msg'] ==
'true') {
$result='<div class="alert alert-success">Thank You ! We will be in touch
soon</div>';
echo $result;
} ?>
<br style="clear:both">
<h3 style="margin-bottom: 25px; text-align: center;">Contact a Conveyancing Property Lawyer Now</h3>
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="email" name="email" placeholder="Email" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Contact Number" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<select name="situation" id="situation">
<option>Select Current Situation</option>
<option class="placeholder" value="Unemployed">Unemployed</option>
<option class="placeholder" value="Employed">Employed</option>
</select>
</div>
<button type="submit" id="submit" name="submit" class="btn btn-primary">Submit</button>

PHP Contact Form 403 Error

In the process of setting up a website for myself, i've hit a bit of a road block with the PHP contact form. I believe it is coded correctly, but whenever I upload it to my site and try to use the contact form I get "Page is forbidden 403". I'm using Hostinger by the way, i've set the permissions of my public_html file to 755. Not sure what the problem could be. Included is my code, any help would be greatly appreciated.
Contact code of the HTML from the index:
<div class="row stay-behind" id="contact">
<h4 class="right-name">Contact</h4>
<div class="col-md-1"></div>
<div class="col-sm-12 col-md-4 feature-image"><img alt="VX1K" height="510" src="images/ux/004.jpg" width="374"> <img alt="VX1K" class="mobile-only" src="images/ux/mobile/004.jpg"></div>
<div class="col-sm-12 col-md-6 main">
<h3 class="title">Contact</h3>
<form class="contact-form" id="contactForm" novalidate method="post" action="public_html/mail/contact_me.php">
<div id="form-alert"></div>
<div class="form-group">
<input class="form-control" id="name" name="name" placeholder="Name" type="name">
</div>
<div class="form-group">
<input class="form-control" id="email" name="email" placeholder="Email" type="email">
</div>
<textarea class="form-control" id="message" placeholder="Message" rows="3"></textarea> <input class="btn btn-block btn-primary" id="btnSubmit" name="submit" type="submit" value="Send">
</form>
</div>
<div class="col-md-1"></div>
Code from the PHP file.
<?php
function Validate()
{
// Check for empty fields
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
return false;
}
else return true;
}
function SendEmail($to = 'noreply#vx1k.com')
{
if (Validate() == true)
{
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
// Create the email and send the message
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n" . "Here are the
details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#vx1k.com\n";
$headers.= "Reply-To: $email_address";
// Send true on successful send.
// Send false if failed
return (mail($to, $email_subject, $email_body, $headers)) ? true : false;
}
else
// Invalid inputs
return 'err';
}
// Apply function(s). You will get true, false, or err
$send = SendEmail();
// On return, you can echo any result
if ($send == 'err') echo 'Invalid Fields.';
elseif ($send == false) echo 'An Error Occurred.';
else echo 'Email Sent Successfully.';
?>

Bootstrap and PHP contact form display blank page when clicking submit [duplicate]

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
Hii guys I need some help.
When I try and test my bootstrap form, it displays a white screen. Here's my code.NB Am newbie to web developing, #ExcuseMyFrenchThough
Here is my index.html
<html>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3" id="offer">
<h2 id="form"> LET'S WORK ? </h2>
</div>
<div class="col-md-6 col-md-offset-3">
<form role="form" method="post" action="contact.php">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Your Name">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
<div class="form-group">
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter Your Email">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
<div class="form-group">
<textarea class="form-control" id="textarea1" rows="3" placeholder="Enter Your Message here"> </textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
<div class="form-group">
<button type="submit" class="default-submit btn btn-large propClone bg-fast-pink btn-circle font-weight-300 text-white tz-text">SEND MESSAGE</button>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</form>
</div>
</div>
</div>
PHP CODE [CONTACT.PHP]
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
/*$human = intval($_POST['human']); */
$from = 'Geofrey Zellah';
$to = 'hotbonge#gmail.com';
$subject = 'Message from Geofrey Zellah ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
/*
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
} */
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage /*&& !$errHuman*/) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
Screenshot of what I get after I click submit on my page, NB live not local
anyone ?
The submit variable is never set in your form. Note the button is now an input of the type submit with the name attribute of submit.
Also your other form variables were not set.
You were never echoing anything. So i put an echo in your last condition.
If you want the form to display after submitting the form, you need to rename your index.html to index.php and include contact.php at the top. See below.
If you just plainly check if a $_POST variable is true, PHP will throw E_NOTICE errors. So best wrap the variable into the isset() (as in is this variable set) function. See below.
I refactored to prevent E_NOTICE errors and commented the changes.
contact.php
<?php
if (isset($_POST["submit"])) {
$error = [];
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
/*$human = intval($_POST['human']); */
$from = 'Geofrey Zellah';
$to = 'hotbonge#gmail.com';
$subject = 'Message from Geofrey Zellah ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
// Check if name has been entered
if (!isset($_POST['name']) || strlen($_POST['name']) === 0) {
$error['name'] = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error['email'] = 'Please enter a valid email address';
}
//Check if message has been entered
if (!isset($_POST['message']) || strlen($_POST['name']) === 0) {
$error['message'] = 'Please enter your message';
}
/*
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
} */
// If there are no errors, send the email
if (empty($error)) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
index.php <-- Note the change of file extension
<?php include 'contact.php';?>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3" id="offer">
<h2 id="form"> LET'S WORK ? </h2>
</div>
<div class="col-md-6 col-md-offset-3">
<form role="form" method="post">
<div class="form-group">
<input name="name" type="text" class="form-control" placeholder="Enter Your Name">
<?php if(isset($error['name'])) echo '<p class="text-danger">'.$error['name'].'</p>'; ?>
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter Your Email">
<?php if(isset($error['email'])) echo '<p class="text-danger">'.$error['email'].'</p>'; ?>
</div>
<div class="form-group">
<textarea name="message" class="form-control" id="textarea1" rows="3" placeholder="Enter Your Message here"> </textarea>
<?php if(isset($error['message'])) echo '<p class="text-danger">'.$error['message'].'</p>'; ?>
</div>
<div class="form-group">
<input name="submit" type="submit" class="default-submit btn btn-large propClone bg-fast-pink btn-circle font-weight-300 text-white tz-text">SEND MESSAGE</input>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php if(isset($result)) echo $result; ?>
</div>
</div>
</form>
</div>
</div>
</div>
UPDATE
If you do not want a reload of the page when submitting the form, you will need some jQuery ajax action and alter your HTML and PHP file.
First remove the first line of your index.php that we added before:
<?php include 'contact.php';?><!-- Remove this one -->
You do not want the file to be included, but rather send data to it.
Next edit the HTML file and include jQuery library underneath your HTML (common practice to do JS stuff below HTML). Then alter your PHP file accordingly.
So your new HTML:
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3" id="offer">
<h2 id="form"> LET'S WORK ? </h2>
</div>
<div class="col-md-6 col-md-offset-3">
<form role="form" name="contact" method="post">
<div class="form-group">
<input name="name" type="text" class="form-control" placeholder="Enter Your Name" value="test">
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter Your Email" value="giroteam#localhost.com">
</div>
<div class="form-group">
<textarea name="message" class="form-control" id="textarea1" rows="3" placeholder="Enter Your Message here">test </textarea>
</div>
<div class="form-group">
<input name="submit" type="submit" class="default-submit btn btn-large propClone bg-fast-pink btn-circle font-weight-300 text-white tz-text" value="SEND MESSAGE">
</div>
<div class="form-group" id="result">
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){ // launch when DOM is fully loaded
$('form[name="contact"]').submit(function(event){ // fire when you hit submit
event.preventDefault(); // prevent default form submission since you want to send data via ajax
$('#result').html('');
$('.alert').remove();
var values = $(this).serialize();
// Post form data to your contact.php script and work with response
$.ajax({
url: "contact.php",
type: "POST",
data: values ,
success: function (response) {
if(response.success) {
$('#result').html('<div class="alert alert-success">'+response.success+'</div>');
}
if(response.error_form) {
$.each( response.error_form, function( key, value ) {
$('input[name="'+key+'"]').parent().append('<p class="help-block text-danger">'+value+'</p>');
});
}
if(response.error_mail) {
$('#result').html('<div class="alert alert-danger">'+response.error_mail+'</div>');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
And finally the changed PHP:
<?php
ini_set('display_errors',0);
$result = [];
// Check if name has been entered
if (!isset($_POST['name']) || strlen($_POST['name']) === 0) {
$result['error_form']['name'] = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$result['error_form']['email'] = 'Please enter a valid email address';
}
//Check if message has been entered
if (!isset($_POST['message']) || strlen($_POST['message']) === 0) {
$result['error_form']['message'] = 'Please enter your message';
}
/*
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
} */
// If there are no errors, send the email
if (empty($result['error_form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
/*$human = intval($_POST['human']); */
$from = 'Geofrey Zellah';
$to = 'hotbonge#gmail.com';
$subject = 'Message from Geofrey Zellah ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if (mail ($to, $subject, $body, $from)) {
$result['success']='Thank You! I will be in touch';
} else {
$result['error_mail']='Sorry there was an error sending your message. Please try again later';
}
}
header('Content-type: application/json'); // tell browser what to expect
echo json_encode($result); // encode array to json object so javascript can work with it
I made such an elaborate example since many people decide to go ajax once they are successful in sending a regular form but notice that the page reloads ;)
I get what you want to achieve. You want to submit this form and if something is wrong, you want to show some error messages.
What has happened in your case is that, when you submit your form, it gets submitted to contact.php. Your browser will show what you return from the contact.php file. Since your contact.php do not include any HTML content and you don't write anything either, returned page doesn't include anything.
You have two options.
First way:
echo the error messages to the contact.php file. Add the following to the end of contact.php file.
echo $result;
This way, when someone submit your form. You will direct him to a new page which only have some line saying whether there was error or successful.
Second way
Move that logic to your index.html. You have to rename it to index.php. Then set the form to submit to the same page.
<form .... action="">
This will submit the form to the current page, which is index.php. Then, put your logic in contact.php at top of your index.php.

PHP/HTML form post to email not posting data through

I can't get this HTML form to post the data to PHP. The mail comes through ok, and has the titles (i.e. First Name: or Last Name:) but the actual data submitted is blank. What could be wrong with it?
HTML FORM DATA:
<div class="col-md-4 col-sm-12">
<div class="contact-form bottom">
<a name="contact" class="more scrolly"></a>
<h2>We'll call you back!</h2>
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" name="first" class="form-control" required placeholder="First Name">
</div>
<div class="form-group">
<input type="text" name="last" class="form-control" required placeholder="Last Name">
</div>
<div class="form-group">
<input type="tel" name="phone" class="form-control" required placeholder="Phone Number">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" required placeholder="Email">
</div>
<div class="form-group">
<select input type="text" name="debt" class="form-control">
<option value="Debt_Level">Debt Level</option>
<option value="-">-</option>
<option value="3000-5000">£3000-£5000</option>
<option value="6000-1000">£6000-£10,000</option>
<option value="11000+">£11,000+</option>
</select>
</div>
<div class="form-group">
<input type="occupancy" name="occupancy" class="form-control" required placeholder="Occupancy">
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-submit" value="Submit">
</div>
</form>
</div>
</div>
PHP FORM DATA:
<?php
// if(!isset($_POST['submit']))
if(!empty($_POST['first']) && !empty($_POST['last']) && !empty($_POST['phone']) && !empty($_POST['email']) && !empty($_POST['purpose']) && !empty($_POST['amount']) && !empty($_POST['mortgage']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$debt = $_POST['debt'] ;
$occupancy = $_POST['occupancy'] ;
$email_from = 'trustmoney.co.uk';//<== update the email address
$email_subject = "Landing Page App'";
$email_body = "You have received a new application request from: $email \n".
"First Name:” $first “\n".
"Last Name: “$last “\n".
"Telephone: “$phone “\n".
"Email: “$email “\n".
"Debt Amount:”$debt “\n".
"Occupancy: “$occupancy “\n".
"\n".
"\n".
"Sent from trustmoney.co.uk to: “\n".
$to = "matt.mckracken#trustmoney.co.uk \n";//<== update the email address
$headers = "From: $email_from";
//$headers .= "Reply-To: $email ";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
?>
The logic of you PHP doesn't really make sense. As #Epodax has pointed out you are checking if the input value aren't empty, then outputting an error saying they are but the email code is not even inside the IF function.
Your strings where you output the data aren't concatenated properly either.
$email_body = echo "You have received a new application request from:".$email."\n".
"First Name:".$first."\n".
"Last Name: "$last "\n". REST_OF_CODE_HERE
A better structure for managing your form validation would be breaking it down for the user and returning them to the form with appropriate errors.
Something like
$_SESSION['POST_VARS'] = $_POST;
$errors = 0;
if(empty($_POST['first'])) {
$_SESSION['errorFirst'] = "Cannot Be Blank, Contain Numbers or Special Characters";
$errors++;
}
if(empty($_POST['last'])) {
$_SESSION['errorLast'] = "Cannot Be Blank, Contain Numbers or Special Characters";
$errors++;
}
Then count the errors
if($errors == 0) {
// Your Submit Email Code
} else {
require( "YOUR_FORM_HERE.php" );
}
Then you can just output the correct session variable in your form with the appropriate error displayed
if(isset($_SESSION['errorFirst'])) { echo "<div class=\"validateError\">" . $_SESSION['errorFirst'] . "</div>"; unset($_SESSION['errorFirst']); };
Also you can return the users original values to the form so they don't have to start from scratch.
<input type="text" name="first" class="form-control" value="<?php if(!empty($_SESSION['POST_VARS']['first'])) { echo $_SESSION['POST_VARS']['first']; }; ?>"/>
Using this method you'll be able to output all the errors in your form to you users.
There is an error in your logic implementation.You Should use an || instead of && as follows
if(empty($_POST['first']) || empty($_POST['last']) || empty($_POST['phone']) || empty($_POST['email']) || empty($_POST['purpose']) || empty($_POST['amount']) || empty($_POST['mortgage']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}

Categories