I am trying to display the name from the input field on a contact form to show the name that was entered after the email was submitted, I have changed headers in php and it has changed from cgi-mailer to unbknown sender? How do i get it to display the name of the person whosent the email from the contact form?
Thanks
form process php that controls validtion etc
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
$from = $_POST['name1'];
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = "From:" . $from;
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
/*if(isset($_POST['submit'])) {
$from = $_POST['name1'];
$headers = "From:" . $from;
}*/
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Conotact form html
<?php include('form_process.php');
/*if (isset($_POST['contact-submit'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "secretkeygoogle";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADOR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true) {
}else{
}
}*/
?>
<div class="home-btn"><i class="fas fa-home"></i></div>
<div class='grey'>
<div class="container-contact">
<form id="contact" method="post">
<div id="column-contact-left">
<div class='contact-logo'></div>
<h3>Contact the Devon Food Movement</h3>
<fieldset>
<input placeholder="Your name" type="text" tabindex="1" name="name1" value="<?= $name ?>" autofocus>
</fieldset>
<span class="error"><?= $name_error ?></span>
<fieldset>
<input placeholder="Your Email Address" type="text" name="email" value="<?= $email ?>" tabindex="2" >
</fieldset>
<span class="error"><?= $email_error ?></span>
</div>
<div id="column-contact-right">
<fieldset>
<textarea placeholder="Type your Message Here...." name="message" value="<?= $message ?>" tabindex="3" ></textarea>
</fieldset>
<div class="g-recaptcha" data-sitekey="needtoinput" ></div>
<span class="success"><?= $success; ?></span>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
</div>
</form>
</div>
</div>
New form p[rocess php with seperate mail function
<?php
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
/*if(isset($_POST['submit'])) {
$from = $_POST['name1'];
$headers = "From:" . $from;
}*/
}
$from = $_POST['name1'];
$headers = "From:" . $from;
if (isset($_POST['submit'])) {
mail($headers);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
LATEST PHP for the last comment i made
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$email = $_POST['email'];
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = 'From:' . $email . "\n" . 'Reply-to: ' . $email . "\n" ;
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
You must have the required fields on your form, then if you want, ask for the name too.
<?php
function defaultMailing($to, $subject, $txt, $headers){
if(mail($to, $subject, $txt, $headers)) return true; else return false;
}
?>
on the other part (where your form action):
$to = $_POST['to'];
$subject = $_POST['subject'];
$txt = $_POST['message'];
//you don't need name, but if you asked for on the form:
$msg = "thanks, ".$_POST['name']." for your message, your request will be answered soon.";
//call to mail function and send the required (to, subject and text/html message) and the optional headers if you want
defaultMailing($to, $subject, $txt, $headers);
//do whatever you want with $msg or with $_POST['name'];
If you want to insert the posted name on the message, simply modify $txt var setting the $_POST['name'] wherever you want and then, proceed with defaultMailing call, for example:
$to = $_POST['to'];
$subject = $_POST['subject'];
$txt = $_POST['message'];
$name = $_POST['name'];
$mailMessage = $name.' '.$txt;
//call to mail function and send the required (to, subject and text/html message) and the optional headers if you want
defaultMailing($to, $subject, $mailMessage, $headers);
Settles for the email being the from sender as it appears that a from value has to be a valid email address
if ($name_error == '' and $email_error == '' and ($res['success']) ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$email = $_POST['email'];
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = 'From:' . $email . "\n" . 'Reply-to: ' . $email . "\n" ;
if (mail($to, $subject, $message, $headers)) {
$sent = "Message sent";
$name = $email = $message = '';
}
Related
I am making a custom contact form via html5 and php. I have got the form looking like I want and am trying to check if the values entered in the fields are working. I am print_r($_POST) to display the arrays.
When clicking the submit button it is not displaying the array but opening the index.html file instead?
The code is as follows...
Contact template calling in the form php file
<?php
/**
* Template Name: contact
*/
get_header();
if (have_posts()) :
while (have_posts()) : the_post();
get_template_part('form');
endwhile;
else:
echo '<p>No Content found</p>';
endif;
?>
</body>
Template part form.php (html layout)
<?php include('form_process.php'); ?>
<div class='grey'>
<div class="container-contact">
<form id="contact" action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
<div class='contact-logo'></div>
<h3>Contact the Devon Food Movement</h3>
<fieldset>
<input placeholder="Your name" type="text" tabindex="1" name="name" autofocus>
<span class="error"><?= $name_error ?></span>
</fieldset>
<fieldset>
<input placeholder="Your Email Address" type="text" name="email" tabindex="2" >
</fieldset>
<fieldset>
<textarea placeholder="Type your Message Here...." name="message" tabindex="3" ></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
</form>
</div>
</div>
And this is the following form being called in form.php = (form_process.php)
<?php
print_r($_POST);
// define variables and set to empty values
$name_error = $email_error = $phone_error = $url_error = "";
$name = $email = $phone = $message = $url = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'vladi#clevertechie.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
$name = $email = $phone = $message = $url = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Why is the submit button opening index.html?
I would make a snippet but dont know how to do this with multiple templates being called in?
Thanks.
UPDATE OF form_process.php file after removing the invalid variables where there are no longer input boxes holding those values
print_r($_POST);
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'info#devonfoodmovement.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
$name = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Instead of using $_SERVER['PHP_SELF'] in your template file's form action, use full path to your form_process.php file.
$_SERVER['PHP_SELF'] returns:
The filename of the currently executing script, relative to the
document root. For instance, $_SERVER['PHP_SELF'] in a script at the
address http://example.com/foo/bar.php would be /foo/bar.php.
Edit:
Here is some solution for you to not redirects to another page:
Template part form.php (html layout):
<?php include('form_process.php'); ?>
<div class='grey'>
<div class="container-contact">
<form id="contact" method="post">
<div class='contact-logo'></div>
<h3>Contact the Devon Food Movement</h3>
<fieldset>
<input placeholder="Your name" type="text" tabindex="1" name="name1" autofocus>
<span class="error"><?= $name_error ?></span>
</fieldset>
<fieldset>
<input placeholder="Your Email Address" type="text" name="email" tabindex="2" >
</fieldset>
<fieldset>
<textarea placeholder="Type your Message Here...." name="message" tabindex="3" ></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
</form>
</div>
</div>
form_process.php file:
<?php
print_r($_POST);
// define variables and set to empty values
$name_error = $email_error = $phone_error = $url_error = "";
$name = $email = $phone = $message = $url = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'vladi#clevertechie.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
$name = $email = $phone = $message = $url = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Please guys am in deep trouble, i have being sweating hard for the past 24 hours, i have this contact form which i uploaded to my server, but the sad part is that, it is only sending the message body to my email, ignoring the other fields like name field, email field and phone number. I am tired of staring at the php code, i feel everything is ok but the code is not working as expected, please help me.
Here is my php code:
<?php
// define variables and set to empty values
$name_error = $email_error = $phone_error = $url_error = "";
$name = $email = $phone = $message = $url = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone_error = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
$phone_error = "Invalid phone number";
}
}
if (empty($_POST["url"])) {
$url_error = "";
} else {
$url = test_input($_POST["url"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$url)) {
$url_error = "Invalid URL";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'emmanuelgbnn23#gmail.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
$name = $email = $phone = $message = $url = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Here is my html code:
<?php include('form_process.php'); ?>
<link rel="stylesheet" href="form.css" type="text/css">
<div class="container">
<form id="contact" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]) ?>" method="post">
<h3>Contact</h3>
<h4>Contact us today, and get reply with in 24 hours!</h4>
<fieldset>
<input placeholder="Your name" type="text" name="name" value="<?= $name ?>" tabindex="1" autofocus>
<span class="error"><?= $name_error ?></span>
</fieldset>
<fieldset>
<input placeholder="Your Email Address" type="text" name="email" value="<?= $email ?>" tabindex="2">
<span class="error"><?= $email_error ?></span>
</fieldset>
<fieldset>
<input placeholder="Your Phone Number" type="text" name="phone" value="<?= $phone ?>" tabindex="3">
<span class="error"><?= $phone_error ?></span>
</fieldset>
<fieldset>
<input placeholder="Your Web Site starts with http://" type="text" name="url" value="<?= $url ?>" tabindex="4" >
<span class="error"><?= $url_error ?></span>
</fieldset>
<fieldset>
<textarea value="<?= $message ?>" name="message" tabindex="5">
</textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
<div class="success"><?= $success ?></div>
</form>
</div>
You are using wrong variable $message in your mail() function. Since you are appending values into $message_body replace $message with $message_body in your script and try again.
<?php
// define variables and set to empty values
$name_error = $email_error = $phone_error = $url_error = "";
$name = $email = $phone = $message = $url = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone_error = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
$phone_error = "Invalid phone number";
}
}
if (empty($_POST["url"])) {
$url_error = "";
} else {
$url = test_input($_POST["url"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$url)) {
$url_error = "Invalid URL";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'emmanuelgbnn23#gmail.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message_body)){
$success = "Message sent, thank you for contacting us!";
$name = $email = $phone = $message = $url = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Change your code
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' )
To this
if ($name_error == '' && $email_error == '' && $phone_error == '' && $url_error == '' )
Learn php operators here
I have a validation for my contact form that adds a red text font under required inputs. But what I really want is to add a red border-bottom to the bottom of the input to show it needs to be required. I have an already working php switch case but can not find the answer anywhere to add css classes to different cases. I hope someone knows more about this than I do.
Here is my php
<?php
session_start();
// define variables and set to empty values
$nameErr = $emailErr = $phoneErr = $humanErr = "";
$Name = $Email = $Phone = $Human = "";
$hasError = false;
$sent = false;
if(isset($_POST['submit'])) {
$Name = trim(htmlspecialchars($_POST['Name'], ENT_QUOTES));
$FName = trim($_POST['FiancesName']);
$Email = trim($_POST['Email']);
$DesiredWedDate = trim($_POST['DesiredWedDate']);
$WeddingSize = trim($_POST['WeddingSize']);
$Phone = trim($_POST['Phone']);
$IndoorCeremony = trim($_POST['IndoorCeremony']);
$OutdoorCeremony = trim($_POST['OutdoorCeremony']);
$AlcoholYes = trim($_POST['AlcoholYes']);
$AlcoholNo = trim($_POST['AlcoholNo']);
$Human = trim($_POST['Human']);
$Number = 6;
$fieldsArray = array(
'Name' => $Name,
'Email' => $Email,
'Phone' => $Phone,
'Human' => $Human
);
$errorArray = array();
foreach($fieldsArray as $key => $val) {
switch ($key) {
case 'Name':
if(empty($val)) {
$hasError = true;
$nameErr = "Please enter your name.";
}
case 'Name':
if (!preg_match("/^[a-zA-Z ]*$/", ($val))) {
$hasError = true;
$nameErr = "The value must be alphanumeric.";
}
break;
case 'Phone':
if (!preg_match("/^[0-9]+$/", ($val))) {
$hasError = true;
$phoneErr = "Only numbers and white space allowed.";
}
case 'Phone':
if(empty($val)) {
$hasError = true;
$phoneErr = "Phone is required.";
}
break;
case 'Email':
if(!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
$hasError = true;
$emailErr = "Email is required.";
} else {
$Email = filter_var($Email, FILTER_SANITIZE_EMAIL);
}
break;
case 'Human':
if (!preg_match("/[^\d]?6[^\d]?/", ($val))) {
$hasError = true;
$humanErr = "Not the right answer";
}
case 'Human':
if (!preg_match("/^[0-9]+$/", ($val))) {
$hasError = true;
$humanErr = "Must be a number";
}
case 'Human':
if(empty($val)) {
$hasError = true;
$humanErr = "Are you human?";
}
break;
}
}
//CHECK BOX WRITE UP
if (isset($_POST['IndoorCeremony'])) {
$checkBoxValue = "yes";
//is checked
} else {
$checkBoxValue = "no";
//is unchecked
}
if (isset($_POST['OutdoorCeremony'])) {
$checkBoxValue = "yes";
//is checked
} else {
$checkBoxValue = "no";
//is unchecked
}
if (isset($_POST['AlcoholYes'])) {
$checkBoxValue = "yes";
//is checked
} else {
$checkBoxValue = "no";
//is unchecked
}
if (isset($_POST['AlcoholNo'])) {
$checkBoxValue = "yes";
//is checked
} else {
$checkBoxValue = "no";
//is unchecked
}
//Validation Success!
//Do form processing like email, database etc here
if($hasError !== true) {
$priority = $_POST['priority'];
$type = $_POST['type'];
$message = $_POST['message'];
//FOR STYLING EMAIL
// $headers .= "MIME-Version: 1.0" . "\r\n";
//$headers .= "Content-Type: text/html; charset=UTF-8" . "\r\n";
//STYLING EMAIL
/* $message = "<html>
<h1>
$Name
</h1>
<BR>
<h3>
$Email
<BR>Tel: $Phone
<BR>Company: $Compnay
<BR>Website: $Website
<BR>Subject: $Subjectmatter
<BR>Describe: $Describe
</h3>
<BR>
<BR>
<BR><h4>Web Design: $webdesign
<BR>Web Hosting: $webhosting
<BR>Wordpress Design: $wordpressdesign
<BR>Logo Design: $logodesign
<BR>Brochures: $brochures</h4>
<BR>
<BR>
<h4>
Other: $otherswitch
<BR>Describe: $OtherDescribe
</h4>
</html>";
*/
$formcontent=" From: $Name \n \n Fiance's Name: $FName \n \n Email: $Email \n \n Phone: $Phone \n \n Desired Wedding Date: $DesiredWedDate \n \n Wedding Size: $WeddingSize \n \n Describe: $Describe \n \n Indoor Ceremony: $IndoorCeremony \n \n Outdoor Ceremony: $OutdoorCeremony \n \n Alcohol Yes: $AlcoholYes \n \n Alcohol No $AlcoholNo \n \n Referral: $Referral \n ";
$recipient = "Youremail#email.com";
$subject = "Pre Book Wedding Contact Form";
$mailheader = "From: $Email \r\n";
mail($recipient, $subject, $formcontent, $mailheader /*$message, $headers*/);
header("Refresh:0; url=thanks.php");
exit();
}
}
?><!--END PHP-->
Here is my input form
<span class="input input--kaede">
<input name="FiancesName" class="input__field input__field--kaede" type="text" id="input-2" />
<label class="input__label input__label--kaede" for="input-2">
<span class="input__label-content input__label-content--kaede">Fiance's Name</span>
</label>
</span>
The css I want to add
I called it
.under_text_error {
border-bottom: 2px solid red;
}
that should hopefully give someone enough to go off of. I appreciate any possible help!
Hope this helps
<?php
if(!empty($nameErr))
{
?>
<div class="under_text_error">
<?php echo $nameErr ?>
</div>
<?php
}
?>
Here is the solution
<span class="input input--kaede <?php echo $FnameErr ?>">
<?php
if(!empty($FnameErr))
{
?>
<div class="under_text_error">
</div>
<?php
}
?>
<input name="FName" class="input__field input__field--kaede " type="text" id="input-2" value="<?php echo (isset($FName) ? $FName : ""); ?>"/>
<label class="input__label input__label--kaede " for="input-2">
<span class="input__label-content input__label-content--kaede ">Fiance's Name</span>
</label>
</span>
Just echo the error class if the field has an error
Something like:
<input class="input__field input__field--kaede <?=isset($nameErr)? 'under_text_error':''?>" />
Okay here is what I tried.
<span class="input input--kaede <?php echo $nameErr ?>">
<?php
if(!empty($nameErr))
{
?>
<div class="under_text_error">
</div>
<?php
}
?>
<input name="Name" class="input__field input__field--kaede " type="text" id="input-2" />
<label class="input__label input__label--kaede " for="input-2" value="<?php echo (isset($Name) ? $Name : ""); ?>">
<span class="input__label-content input__label-content--kaede ">Fiance's Name</span>
</label>
</span>
What this ends up doing is putting the red line on the input and when i fill it in and submit it disappears like its suppose to. The problem now is that the input information (what you type in disappears) it doesn't keep it.
Here is before you fill or submit
Ignore the top red. I was just testing other options. but as you can see the line works here after submit and no answer.
Here is a shot of filling answer in. once submitted it looks like image 1, but blank.
Here is what it looks like last after submit. So it forgets
I'm trying to get the optin form on my website to not send empty fields.
I also have predefined text within the form fields (Ex. "Enter you name here" ) that disappears on click. I don't want the form to send predefined text data either.
What is the best way to go about this with PHP?
HTML:
<div class="form">
<h2>Get An Appointment: <font size="3"><font color="#6E5769">Fill in the form below now, and I'll call you to setup your next dental appointment...</font></font></h2>
<p id="feedback"><?php echo $feedback; ?></p>
<form action="contact.php" method="post"/>
<p class="name">
<input type="text" name="name" id="name" style="text-align:center;" onClick="this.value='';" value="Enter your name"/>
PHP:
<?php
$to = 'test#mywebsite.com'; $subject = 'New Patient';
$name = $_POST['name']; $phone = $_POST['phone'];
$body = <<<EMAIL
Hi, my name is $name, and phone number is $phone.
EMAIL;
$header = 'From: test#mywebsite.com';
if($_POST){ if($name != '' && $phone != ''){ mail($to, $subject, $body, $header); }else{ $feedback = 'Fill out all the fields'; } } ?>
Collect all information in POST array and then remove the empty values using array_filter
Added an sample http://codepad.org/ZtR6Eh93
Heres try this:
<?php
$to = 'test#mywebsite.com';
$subject = 'New Patient';
$header = 'From: test#mywebsite.com';
$feedback = null;
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$name = (!empty($_POST['name'])?$_POST['name']:null);
$phone = (!empty($_POST['phone'])?$_POST['phone']:null);
$body = <<<EMAIL
Hi, my name is $name, and phone number is $phone.
EMAIL;
if($name !== null && $phone !== null){
mail($to, $subject, $body, $header);
$feedback = 'Message Sent';
}else{
$feedback = 'Fill out all the fields';
}
}
?>
For first you should do validation on client-side using JavaScript.
<?
$name = $phone = $status= '';
if(isset($_POST['submit'])){
$name = (!empty($_POST['name'])?$_POST['name']:null);
$phone = (!empty($_POST['phone'])?$_POST['phone']:null);
if($name !== null && $phone !== null){
mail($to, $subject, $body, $header);
$name = $phone = '';
$status = 'Message Sent';
}
else
$status= 'Fill out all the fields';
}
<? if(!empty($status)): ?><p class="error"><?=$status?></p><? endif; ?>
<input type="text" name="name" value="<?=$name?>"/>
<input type="text" name="phone" value="<?=$phone?>"/>
<input type="submit" name="submit" value="send"/>
I'd recommend you use empty() on the $_POST variables, preferably on the required form field (Not just $_POST). For example:
if(!empty($_POST['name'])) {
// Name field was posted
}
This is different to isset because isset will return true if the field was something like "" or NULL. Whereas !empty only accepts values that are not empty / not null. Hence why the empty function is a better choice in this case.
Hope that helps.
Add onsubmit handler to your form that set disabled property to true for all inputs which you don't like to be sent
Update:
This does not relax the requirement to check all input parameters at PHP side of your app.
You can prevent this by checking in the server side:
if($_POST){ if($name != '' && $phone != '' && $name!='Enter your name' && $email!='Enter your email'){ mail($to, $subject, $body, $header); }else{ $feedback = 'Fill out all the fields'; } } ?>
But I suggest that you improve your error handling to something like this:
if ($_POST) {
$err = array();
if ($name == '' || $name == 'Enter your name') $err[] = 'Name is required';
if ($email == '' || $email == 'Enter your email') $err[] = 'Email is required';
if (empty($err)) {
mail($to, $subject, $body, $header);
} else {
$feedback = 'Fill out all fields. Errors: '.implode(', ',$err);
}
}
So I have a form with both javascript validation to check each field is filed and a jquery ajax script to stop the page reloading.
The PHP script is very simple and only emails the fields of the form.
The problem is I need to ONLY show the thank you message if each field is filled out, and at the moment it appears to be showing it when I just enter the name field.
It doesn't show it if i just enter either the email or message field though and I can't work out why (I'm bad at PHP).
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$priority = $_POST['priority'];
$message = $_POST['message'];
$telephone = $_POST['telephone'];
$formcontent="From: $name \n Email: $email \n Telephone Number: $telephone \n Priority: $priority \n Message: $message";
$recipient = "myemail#address.co.uk";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
if(mail($name,$email,$message,$headers)){
echo "<p>Thanks for your mail...</p>";
}
?>
Javascript that stops page reloading.
<script type="text/javascript">
$(document).ready(function() {
$(".contactus").submit(function() {
$.post("mail.php", $(".contactus").serialize(),
function(data) {
$("#formResponse").html(data);
}
);
return false;
});
});
</script>
Form validation.
<script type="text/javascript" language="JavaScript">
var FormName = "contactus";
var RequiredFields = "name,email,priority,message";
function ValidateRequiredFields()
{
var FieldList = RequiredFields.split(",")
var BadList = new Array();
for(var i = 0; i < FieldList.length; i++) {
var s = eval('document.' + FormName + '.' + FieldList[i] + '.value');
s = StripSpacesFromEnds(s);
if(s.length < 1) { BadList.push(FieldList[i]); }
}
if(BadList.length < 1) { return true; }
var ess = new String();
if(BadList.length > 1) { ess = 's'; }
var message = new String('\n\nThe following field' + ess + ' are required:\n');
for(var i = 0; i < BadList.length; i++) { message += '\n' + BadList[i]; }
alert(message);
return false;
}
function StripSpacesFromEnds(s)
{
while((s.indexOf(' ',0) == 0) && (s.length> 1)) {
s = s.substring(1,s.length);
}
while((s.lastIndexOf(' ') == (s.length - 1)) && (s.length> 1)) {
s = s.substring(0,(s.length - 1));
}
if((s.indexOf(' ',0) == 0) && (s.length == 1)) { s = ''; }
return s;
}
// -->
</script>
And the form
<form action="mail.php" id="myform" class="contactus" onsubmit="return ValidateRequiredFields(); this.submit(); this.reset(); return false;" name="contactus" method="POST">
<p class="floatleft" style="width:200px; background-color:#FF0000; height:50px; line-height:50px; margin:0; padding:0;">Nameeeeee</p> <input class="sizetext" type="text" maxlength="10" name="name">
<div style="clear:both"></div>
<p class="floatleft" style="width:200px;">Email</p> <input class="sizetext" type="text" maxlength="10" name="email">
<div style="clear:both"></div>
<p class="floatleft" style="width:200px;">Telephone</p> <input class="sizetext" type="text" maxlength="10" name="telephone">
<p>Priority</p>
<select name="priority" size="1">
<option value="Low">Low</option>
<option value="Normal">Normal</option>
<option value="High">High</option>
<option value="Emergency">Emergency</option>
</select>
</select>
<p>Message</p><textarea name="message" rows="6" cols="25"></textarea><br />
<br />
<input class="buttonstyle" type="submit" value="Send">
</form>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$priority = $_POST['priority'];
$message = $_POST['message'];
$telephone = $_POST['telephone'];
$check = array('name', 'email', 'priority', 'message', 'telephone');
$send = true;
foreach($check as $key => $value){
if(empty($_POST[$value])){
$send = false;
}
}
$formcontent="From: $name \n Email: $email \n Telephone Number: $telephone \n Priority: $priority \n Message: $message";
$recipient = "myemail#address.co.uk";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
if($send && mail($recipient, $subject, $formcontent, $mailheader)){
echo "<p>Thanks for your mail...</p>";
}
else{
die('Error!');
}
Well, the most easier way would be to check if your POST fields are present and not empty. Probably there is a more elegant solution if you want to check every field individually, but here goes:
if (isset($_POST['name']) && !empty($_POST['name']) && isset($_POST['email']) && !empty($_POST['email']) && isset($_POST['message']) && !empty($_POST['message'])) {
if(mail($name,$email,$message,$headers)){
echo "<p>Thanks for your mail...</p>";
}
}
You need to wrap your code around
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$priority = $_POST['priority'];
$message = $_POST['message'];
$telephone = $_POST['telephone'];
$formcontent="From: $name \n Email: $email \n Telephone Number: $telephone \n Priority: $priority \n Message: $message";
$recipient = "myemail#address.co.uk";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
$mail = #mail($recipient, $subject, $formcontent, $mailheader);
if($mail){
echo "<p>Thanks for your mail...</p>";
}
else
{
echo "Error Sending Mail " ;
}
}