As my discussion title says. Form works fine when submitting all corresponding info, but does not send "Comments" section. Any help would be greatly appreciated.
Here is my Form Code:
<form role="form" id="footerform" name="footform" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<div class="form-group"> <span id="footformerror" class="error"></span>
<input name="footname" id="footname" class="form-control input-sm" placeholder="First Last" pattern="[A-Za-z]+ [A-Za-z]+" value="<?php if (isset($footname)) { echo $footname;} ?>" />
<?php if (isset($err_footname)) { echo $err_footname;}?>
<?php if (isset($err_footpatternmatch)) { echo $err_footpatternmatch;}?>
</div>
<div class="form-group">
<input type="email" name="footemail" class="form-control input-sm" id="footemail" autocomplete="off" required pattern="^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+#([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$" placeholder="example#email.com" value="<?php if (isset($footemail)) { echo $footemail;} ?>" />
</div>
<div class="form-group">
<textarea type="text" name="footcomments" id="footcomments" class="form-control input-sm" rows="6" placeholder="Comments" required></textarea>
<?php if (isset($footcomments)) { echo $footcomments; } ?>
</div>
<button type="submit" name="footsend" class="btn btn-default btn-xs" >Submit</button>
<input type="reset" value="Reset!" class="btn btn-default btn-xs">
</form>
Here is my PHP Coding:
if(isset($_POST['footsend'])) {
if (isset($_POST['footname'])) { $footname = $_POST['footname']; } else { $footname = '';}
if (isset($_POST['footemail'])) { $footemail = $_POST['footemail']; }else { $footemail = '';}
if (isset($_POST['footcomments'])) {$footcomments = filter_var($_POST['footcomments'], FILTER_SANITIZE_STRING );
}
if (isset($_POST['ajaxrequest'])) { $ajaxrequest = $_POST['ajaxrequest']; } else { $footcomments = '';}
$footformerrors = false;
if ($footname === '') :
$err_footname = '<div class="error">Sorry, your name is a required field</div>';
endif; // input field empty
if ( !(preg_match('/[A-Za-z]+ [A-Za-z]+/', $footname)) ) :
$err_footpatternmatch = '<div class="error">Sorry, the name must be in the format: First Last</div>';
endif; // pattern doesn't match
if ( !(preg_match('/^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+#([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/', $footemail)) ) :
$err_footemail = '<div class="error">Sorry, enter valid email address</div>';
endif; // pattern doesn't match
if (strlen($footcomments) < 2) :
$err_footcomments = '<div class="error">Please enter you comment.</div>';
endif; // input field empty
error_reporting(E_ERROR | E_PARSE);
$footemail_to = 'example#email.com';
$footemail_subject = 'Website Footer Comment Submission';
$footemail_from = $footemail;
$footemail_contact = $footname;
$footemail_message = "Email submission from ".$footname." at scdesignprint.net footer comments section.\n\n";
function clean_string($string) {
$bad = array('content-type','bcc:','to:','cc:','href');
return str_replace($bad,"",$string);
}
$footemail_message .= "Name: ".clean_string($footname)."\n";
$footemail_message .= "Email: ".clean_string($footemail)."\n";
$footemail_message .= "Comments: ".clean_string($footcomments)."\n";
$footheaders = "From: ".$footemail_from."\r\n".
"Reply-To: ".$footemail_contact."\r\n" ;
mail($footemail_to, $footemail_subject, $footemail_message, $footheaders);
This line is clearing your comments :
if (isset($_POST['ajaxrequest'])) { $ajaxrequest = $_POST['ajaxrequest']; } else { $footcomments = '';}
This is a contact from using HTML5 and PHP. Works well for me
<label>Name</label>
<input name="name" placeholder="Type Here">
<label>Email</label>
<input name="email" type="email" placeholder="Type Here">
<label>Message</label>
<textarea name="message" placeholder="Type Here"></textarea>
<input id="submit" name="submit" type="submit" value="Submit">
<label>*What is 2+2? (Anti-spam)</label>
<input name="human" placeholder="Type Here">
</form>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: TangledDemo';
$to = 'contact#tangledindesign.com';
$subject = 'Hello';
$human = $_POST['human'];
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($_POST['submit'] && $human == '4') {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
} else if ($_POST['submit'] && $human != '4') {
echo '<p>You answered the anti-spam question incorrectly!</p>';
}
?>
Related
With purpose to save your time I have two screenshots of my contact form.
Also instead of expected result the message "Thank you. Your message has been received" I got in new window. How can I place the message in that input element? Where am I wrong?
You can check my contact form by this link just send any message.
Thank you so much for your time and answers.
<form action="contact/form-handler.php" method="post">
<fieldset>
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" class="form-control" name="name" id="name" placeholder="Your Name"/>
</div>
<div class="form-group col-md-6">
<input type="text" class="form-control" name="email" id="email" placeholder="Your Email"/>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject"/>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
</div>
<div>
<input type="hidden" name="hidden" value="" />
<div class="nocomment">
<label for="nocomment"></label>
<input id="nocomment" class="nocomment" value="" name="nocomment" />
</div>
<div class="text-center">
<input type="submit" value="Send Message" name="submit"/>
<input type="reset" value="Clear Message" name="reset"/>
</div>
</div>
<input type="hidden" name="v_error" id="v-error" value="Required" />
<input type="hidden" name="v_email" id="v-email" value="Enter a valid email" />
</fieldset>
</form>
And my contact/form-handler.php
<?php
include('SMTPClass.php');
$emailto = 'myemail.com';
// retrieve from parameters
$emailfrom = isset($_POST["email"]) ? $_POST["email"] : "";
$nocomment = isset($_POST["nocomment"]) ? $_POST["nocomment"] : "";
$subject = 'Email from InWebWorld';
$message = '';
$response = '';
$response_fail = 'There was an error verifying your details.';
// Honeypot captcha
if($nocomment == '') {
$params = $_POST;
foreach ( $params as $key=>$value ){
if(!($key == 'ip' || $key == 'emailsubject' || $key == 'url' || $key == 'emailto' || $key == 'nocomment' || $key == 'v_error' || $key == 'v_email')){
$key = ucwords(str_replace("-", " ", $key));
if ( gettype( $value ) == "array" ){
$message .= "$key: \n";
foreach ( $value as $two_dim_value )
$message .= "...$two_dim_value<br>";
}else {
$message .= $value != '' ? "$key: $value\n" : '';
}
}
}
$response = sendEmail($subject, $message, $emailto, $emailfrom);
} else {
$response = $response_fail;
}
echo $response;
// Run server-side validation
function sendEmail($subject, $content, $emailto, $emailfrom) {
$from = $emailfrom;
$response_sent = 'Thank you. Your messsage has been received.';
$response_error = 'Error. Please try again.';
$subject = filter($subject);
$url = "Origin Page: ".$_SERVER['HTTP_REFERER'];
$ip = "IP Address: ".$_SERVER["REMOTE_ADDR"];
$message = $content."\n$ip\r\n$url";
// Validate return email & inform admin
$emailto = filter($emailto);
// Setup final message
$body = wordwrap($message);
// Create header
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=utf-8\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\r\n";
// Send email
$mail_sent = #mail($emailto, $subject, $body, $headers);
$response = $mail_sent ? $response_sent : $response_error;
return $response;
}
// Remove any un-safe values to prevent email injection
function filter($value) {
$pattern = array("/\n/", "/\r/", "/content-type:/i", "/to:/i", "/from:/i", "/cc:/i");
$value = preg_replace($pattern, "", $value);
return $value;
}
exit;
?>
If this php code is in contact/form-handler.php than instead of echo $response; you should redirect back to your contact page with the message, like header('Location: contact_page_url?message='.urlencode($response));And in your contact page put below your form:
<script>
function findGetParameter(parameterName) {
var result = null, tmp = [];
location.search.substr(1).split("&").forEach(function (item){
tmp = item.split("=");
if (tmp[0] === parameterName)
result = decodeURIComponent(tmp[1]);
});
return result;
}
document.querySelector('#nocomment').value = findGetParameter('message') || '';
</script>
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>
I'm kinda new in PHP and I've created a form that should validate data and submit an error if any field is blank or incorrect. It doesn't tho. Even if email is wrong or any field is empty and the errors are shown it still sends an email. And the headers are not showing in the message. The only case when the errors are shown and the mail isn't send is the case when all fields are empty. Here's the code:
<?php
$NameErr = $EmailErr = $SubErr = $MessErr = "";
$Name = $Email = $Subject = $Message = "";
$header = "From: " . $Email . "Name: " . $Name . "\r\n";
$header .= "Content-Type: text/plain";
$To = "xxx#gmail.com";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$NameErr = "Name is required";
} else {
$Name = test_input($_POST["Name"]);
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"]);
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
$EmailErr = "Invalid email format";
}
}
if (empty($_POST["Subject"])) {
$SubErr = "Subject is required";
} else {
$Subject = test_input($_POST["Subject"]);
}
if (empty($_POST["Message"])) {
$MessErr = "Message is required";
} else {
$Message = test_input($_POST["Message"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<p><input class="w3-input w3-padding-16" type="text" placeholder="Name" name="Name"></p>
<span class="error"> <?php echo $NameErr; ?></span>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Email" name="Email"></p>
<span class="error"> <?php echo $EmailErr; ?></span>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Subject" name="Subject"></p>
<span class="error"> <?php echo $SubErr; ?></span>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Message" name="Message"></p>
<span class="error"> <?php echo $MessErr; ?></span>
<p>
<button class="w3-btn w3-grey w3-padding-large w3-hover-green" type="submit" value="Submit" name="pressed">
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
</p>
</form>
<?php
if (isset($_POST["pressed"])) {
if (empty($NameErr && $SubErr && $MessErr && $EmailErr)) {
mail($To, $Subject, $Message, $header);
echo "Email sent.";
} else {
echo "Error.";
}
}
?>
Can you help me? Error validating is on and it doesn't show me any errors.
use isset function instead of empty() to check if the field is posted or not.
example:
if (!isset($_POST["Name"])) {
...
also there is no need to check the request method, $_POST will only catch post requests.
So I've re designed the code structure for you. Generally calling a class and a function will keep your files and your code cleaner.
So with this being said, let me show you some insight. This is where your form will be located for example: form.php
<?php
require ('mail.php');
$send = new Mail();
if (isset($_POST['sendIt']))
{
$send->sendMail($_POST['nameP'], $_POST['email'], $_POST['subject'], $_POST['message']); // Call the class and function
}
?>
<form id="contact" method="post">
<div class="container">
<input type="text" name="nameP" placeholder="Name *" /><br />
<input type="email" name="email" placeholder="Email *"/><br />
<input type="text" name="subject" placeholder="Subject *"><br />
<textarea name="message" id="" cols="30" rows="10"></textarea>
<input type="submit" name="sendIt" id="submit">
</div>
</form>
Then create yourself a mail.php file to store the class and the functions revolving around mailing in general:
<?php
class Mail
{
public function sendMail($name, $email, $subject, $message)
{
if (!empty($name))
{
if (!empty($email))
{
if (!empty($subject))
{
if (!empty($message))
{
$email_to = 'Your#emailAddress';
$header = 'From: ' . $name ."<noreply#youremail>". "\r\n" .
'Reply-To: ' . $email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, 'Enquiry Received', 'Name: ' . $name . "\r\n\r\n". 'Email Address: ' .$email."\r\n\r\n" . 'Message: ' .$message."\r\n\r\n". $header);
echo "SUCCESS MESSAGE";
} else {
echo "Please fill in your message";
}
} else {
echo "Please provide a subject.";
}
} else {
echo "Please provide your email address.";
}
} else {
echo "Please provide your name.";
}
}
}
?>
This will generally clear the form if there is an error by default however you can then simply add value="<?php echo $_POST['whateverThisFormIsFor'];?>
I hope this will help and give you some further insight.
The way you're constructing your empty check towards the bottom is incorrect:
if (empty($NameErr && $SubErr && $MessErr && $EmailErr)){
The only way that this will evaluate to false is if all of the error messages are set, and the above snippet will break before PHP 5.5 (as Felippe mentioned in the comments). What you want instead is the below; it returns true only if none of the error messages are set:
if (empty($NameErr)
&& empty($SubErr)
&& empty($MessErr)
&& empty($EmailErr)) {
Another way to do this would be to
extract the validation logic into methods for readability,
read off of an $errors array instead of $NameErr, $SubjectErr, etc.
keep POST logic together (instead of split between the beginning and end)
To those ends, I've rewritten your snippet below:
<?php
function validateName($input)
{
if (empty($input)) {
return 'Name is required';
}
if (preg_match("/^[a-zA-Z ]*$/", $input) != 1) {
return 'Name may only contain letters and spaces';
}
return null;
}
function validateEmail($input)
{
if (empty($input)) {
return 'Email is required';
}
if (filter_var($input, FILTER_VALIDATE_EMAIL)) {
return 'Email is in an invalid format';
}
return null;
}
function validateSubject($input)
{
return empty($input) ? 'Subject is required' : null;
}
function validateMessage($input)
{
return empty($input) ? 'Message is required' : null;
}
function test_input($data)
{
return htmlspecialchars(stripslashes(trim($data)));
}
$errors = [];
$notification = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST['name'] ?: '');
$email = test_input($_POST['email'] ?: '');
$subject = test_input($_POST['subject'] ?: '');
$message = test_input($_POST['message'] ?: '');
if (($error = validateName($name)) !== null) {
$errors['name'] = $error;
}
if (($error = validateEmail($email)) !== null) {
$errors['email'] = $error;
}
if (($error = validateSubject($subject)) !== null) {
$errors['subject'] = $error;
}
if (($error = validateMessage($message)) !== null) {
$errors['message'] = $error;
}
if (empty($errors)) {
$headers = [
"From: $name <$email>",
"Content-Type: text/plain",
];
$to = "xxx#gmail.com";
mail($to, $subject, $message, implode("\r\n", $headers));
$notification = 'The email was sent!';
} else {
$notification = 'The email could not be sent; please check below for errors.';
}
}
?>
<form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<?php if (!empty($notification)): ?><p><?= $notification ?></p><?php endif; ?>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Name" name="name" required></p>
<?php if (isset($errors['name'])): ?><span class="error"> <?= $errors['name'] ?></span><?php endif; ?>
<p><input class="w3-input w3-padding-16" type="email" placeholder="Email" name="email" required></p>
<?php if (isset($errors['email'])): ?><span class="error"> <?= $errors['email'] ?></span><?php endif; ?>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Subject" name="subject" required></p>
<?php if (isset($errors['subject'])): ?><span class="error"> <?= $errors['subject'] ?></span><?php endif; ?>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Message" name="message" required></p>
<?php if (isset($errors['message'])): ?><span class="error"> <?= $errors['message'] ?></span><?php endif; ?>
<p>
<button class="w3-btn w3-grey w3-padding-large w3-hover-green" type="submit">
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
</p>
</form>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
My contact form will not submit and send to my email address..
Here is the PHP validation I am using to check required fields and then to send to my email:
<?php
if (isset($_GET['submit'])) {
$body = '';
$body .= 'Name: ' . $_POST['name'] . "\n\n";
$body .= 'Phone: ' . $_POST['phone'] . "\n\n";
$body .= 'Email: ' . $_POST['email'] . "\n\n";
$body .= 'Message: ' . $_POST['message'] . "\n\n";
mail('myemailaddress#gmail.com', 'Contact Form', $body, 'From: no-reply#mycompany.com');
}
// define variables and initialize with empty values
$nameErr = $addressErr = $emailErr = $messageErr = $spamcheckErr = "";
$name = $address = $email = $message = $spamcheck = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please enter your name.";
}
else {
$name = $_POST["name"];
}
if (empty($_POST["email"])) {
$emailErr = "Please enter your email.";
}
else {
$email = $_POST["email"];
}
if (empty($_POST["message"])) {
$messageErr = "Cannot leave message box blank.";
}
else {
$message = $_POST["message"];
}
if (!isset($_POST["spamcheck"])) {
$spamcheckErr = "Verify you are not spam.";
}
else {
$spamcheck = $_POST["spamcheck"];
}
}
?>
Here is my HTML:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="contact_input" class="col1">
<input name="name" placeholder="Name*" type="text" class="text" value="<?php echo htmlspecialchars($name);?>">
<span class="error"><?php echo $nameErr;?></span><br />
<input name="email" placeholder="Email*" type="email" class="text" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span><br />
<input name="phone" placeholder="Phone #" type="tel" class="text" value="<?php echo $phone;?>" />
</div>
<div id="contact_input" class="col2">
<textarea name="message" placeholder="Message*" rows="10" cols="25"><?php echo $message?></textarea>
<span class="error"><?php echo $messageErr;?></span>
</div>
<div id="contact_input" class="col3">
<input id="spamcheck" type="checkbox" name="spamcheck" value="<?php echo htmlspecialchars($spamcheck);?>">I am human.*<br />
<span class="error"><?php echo $spamcheckErr;?></span>
<input id="submit" type="submit" name="submit" value="Send" class="button" /><br />
<span>*Required Field.</span>
</div>
</form>
When fields are empty I get the proper error message under each field but I cannot get it to send to my email. However it was emailing me every time I loaded the page, when I made these changes it stopped submitting.
Being new to contact forms with required fields, I can't seem to find the clear answer elsewhere.
I suspect it has something to do with if (isset($_GET['submit'])) Since that is where I made the change and started having issues.
You have to add ?submit to the action string in your form or else $_GET['submit'] will be unset.
<form method="post" action="?submit">
or you can change the isset function to check the $_POST var instead of the $_GET var
if (isset($_POST['submit'])) {
EDIT: Here's what you should do with your validation script
if (!empty($_POST['submit'])) {
$error = array();
if (empty($_POST['email'])) $error[] = 'Please enter your email';
// and so on...
if (empty($error)) {
// Send email script goes here
}
}
And then for your user display upon any errors:
if (!empty($error)) foreach ($error as $e) echo '<p class="error">'.$e.'</p>';
This allows you to add more error messages as often as you'd like with ease, and uses the empty property of an array to verify the lack of error in validation.
I tested your code and everything checked out, except for this line:
if (isset($_GET['submit'])) {
which just needs to be changed to:
if (isset($_POST['submit'])) {
The issue was in fact using $_GET instead of $_POST
EDIT
Added a few conditional statements:
if (($_POST['name'] && $_POST['email'] && $_POST['message'] !="")
&& isset($_POST["spamcheck"]) !="")
Full code (use the full version below):
<?php
if (isset($_POST['submit'])) {
$body = '';
$body .= 'Name: ' . $_POST['name'] . "\n\n";
$body .= 'Phone: ' . $_POST['phone'] . "\n\n";
$body .= 'Email: ' . $_POST['email'] . "\n\n";
$body .= 'Message: ' . $_POST['message'] . "\n\n";
if (($_POST['name'] && $_POST['email'] && $_POST['message'] !="") && isset($_POST["spamcheck"]) !="")
{
mail('myemailaddress#gmail.com', 'Contact Form', $body, 'From: no-reply#mycompany.com');
}
}
// define variables and initialize with empty values
$nameErr = $addressErr = $emailErr = $messageErr = $spamcheckErr = "";
$name = $address = $email = $message = $spamcheck = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please enter your name.";
}
else {
$name = $_POST["name"];
}
if (empty($_POST["email"])) {
$emailErr = "Please enter your email.";
}
else {
$email = $_POST["email"];
}
if (empty($_POST["message"])) {
$messageErr = "Cannot leave message box blank.";
}
else {
$message = $_POST["message"];
}
if (!isset($_POST["spamcheck"])) {
$spamcheckErr = "Verify you are not spam.";
}
else {
$spamcheck = $_POST["spamcheck"];
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="contact_input" class="col1">
<input name="name" placeholder="Name*" type="text" class="text" value="<?php echo htmlspecialchars($name);?>">
<span class="error"><?php echo $nameErr;?></span><br />
<input name="email" placeholder="Email*" type="email" class="text" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span><br />
<input name="phone" placeholder="Phone #" type="tel" class="text" value="<?php echo $phone;?>" />
</div>
<div id="contact_input" class="col2">
<textarea name="message" placeholder="Message*" rows="10" cols="25"><?php echo $message?></textarea>
<span class="error"><?php echo $messageErr;?></span>
</div>
<div id="contact_input" class="col3">
<input id="spamcheck" type="checkbox" name="spamcheck" value="<?php echo htmlspecialchars($spamcheck);?>">I am human.*<br />
<span class="error"><?php echo $spamcheckErr;?></span>
<input id="submit" type="submit" name="submit" value="Send" class="button" /><br />
<span>*Required Field.</span>
</div>
</form>
I don't understndand if (isset($_GET['submit'])) in fact. Why is it there?
$field1 = NULL;
$field2 = NULL;
if(isset($_POST["submit"])){
$field1 = $_POST["field1"];
$field2 = $_POST["field2"];
//etc
mail ("youremail", "yoursubject", "$field1 $field2 $field3 etc.");
}
I have a simple contact form appearing on a modal in bootstrap. For some reason my form will not send. I've been looking at it for the last few hours and could use a fresh pair of eyes. It seems so simple but I'm at a total loss.
I've put a non-displayed textfield in the form as a spam filter. Since most bots would fill the textfield I want the code to send only if the textfield is blank (which it should be if the user is human since it's not displayed).
index.php
<div class = "modal fade" id = "contact" role = "dialog">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<a id = "btn-close" data-dismiss = "modal">X</a>
</div>
<form>
<form method="post" action="index.php">
<fieldset id= "contact-fieldset">
<input name="name" type="text" id="name" class="text-input" placeholder="First and last name" required>
<input name="email" type="email" placeholder="Email address" required>
<textarea name="message" placeholder="Your Message" required></textarea>
<input name="bot-catch" type="text" id="bot-catch">
<input id="submit" class="submit-btn" name="submit" type="submit" value="Submit">
</fieldset>
</form>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: Me';
$to = 'me#email.com';
$subject = 'Hello';
$human = $_POST['bot-catch'];
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($_POST['submit'] && $human == '') {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
} else if ($_POST['submit'] && $human != '') {
echo '<p>You answered the anti-spam question incorrectly!</p>';
}
?>
</form>
<div class = "modal-footer">
</div>
</div>
</div>
</div>
EDIT: So I have now gotten my message to send, but only if I put the PHP code into a separate file and link to it by . Only problem is- I do not want the user to be directed off of my page once they send a message. Is there anything I can do? I still can't figure out why it won't send on my index page.
EDIT: Well I got it working!! Thank you for all your help!