PHP email form not posting name or phone number - php

I can't seem to figure out why my php isn't sending the name and phone number to the email. Email and message is working fine.
Here is my HTML:
<form method="POST" name="contact_form" action="php.php">
<label for='fname'>Name: </label>
<input type="text" name="fname">
<label for='email'>Email: </label>
<input type="text" name="email">
<label for='phone'>Phone: </label>
<input type="text" name="phone">
<label for='message'>Message:</label>
<textarea name="message" rows=8 cols=30><?php echo htmlentities($user_message) ?></textarea>
<label><img src="/captcha.php"></label>
<input type="text" name="code" value="Please enter the code"> <br />
<input type="submit" value="Submit" name='submit' class="quoteButton">
</form>
Here is my PHP:
session_start();
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['fname'])) {
$name = $_POST['fname'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['phone'])) {
$name = $_POST['phone'];
} else {
$error .= "You didn't enter your phone. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "You didn't type in a message. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try again. <br />";
}
if (empty($error)) {
$from = 'From: ' . $fname . ' <' . $email . '>';
$to = "mail#domain.com";
$subject = "New contact form message";
$content = $fname . " has sent you a message. \nEmail: $email \nPhone: $phone \nMessage: \n" . $message;
$success = header( 'Location: '' ) ;
mail($to,$subject,$content,$from);
}
}
?>
Any help would be greatly appreciated. Thanks!

1)You named the variable for first name $name but use $fname in the email portion of code
$name = $_POST['fname'];
should be
$fname = $_POST['fname'];
2) You named the variable for first name $name (overwriting your initial assignment) but use $phone in the email portion of code
$name = $_POST['phone'];
should be
$phone = $_POST['phone'];

Related

PHP - Form field validation

I have a form that takes in data i am using php to send it to my email once a user has filled in all the required fields. If a field is empty I get a message eg. "Email is required" but the email still sends. I dont know what the problem is any ideas? Idont want to send a email if any field is empty i also dont want refresh the page everytime submit is clicked, I would like to instead just show the "Required message".
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$nameErr = $lastNameErr = $emailErr = $ironingErr = $descriptionErr = $RoomErr = "";
$first_name = $last_name = $email = $ironing = $description = $Rooms ="";
if(isset($_POST['submit'])){
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$ironing = $_POST['ironing'];
$Rooms = $_POST['Rooms'];
$Description = $_POST['description'];
if (empty($_POST["first_name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["first_name"]);
// check if name only contains letters and whitespace
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"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["description"])) {
$descriptionErr = "Description is required";
} else {
$description = test_input($_POST["description"]);
}
if (empty($_POST["Rooms"])) {
$RoomErr = "Room number is Required";
} else {
$Rooms = test_input($_POST["Rooms"]);
}
if (empty($_POST["ironing"])) {
$ironingErr = "Ironing is Required";
} else {
$ironing = test_input($_POST["ironing"]);
}
$to = "someemail#gmail.com"; // this is your Email address
$subject = "Order Sumbittion";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['description']. "\n\n" . "Number of Rooms: ". "\n\n" . $_POST['Rooms'] ."Ironing: " . $_POST['ironing'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['description']. "\n\n" . "Number of Rooms: " . "Number of Rooms: " . $_POST['Rooms'] ."Ironing: ". $_POST['ironing'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2);
// sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
header("Location: index.php");
}
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
<p><span class="error">* required field.</span></p>
<div class="col-md-9">
<form action="" method="post">
First Name: <input type="text" name="first_name">
<span class="error">* <?php echo $nameErr;?></span><br>
<br>
Last Name: <input type="text" name="last_name">
<span class="error">* <?php echo $lastNameErr;?></span><br>
Email:
<br>
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br>
Ironing?<br>
<input type="radio" name="ironing" <?php if (isset($ironing) && $ironing=="Yes") echo "checked";?> value="Yes">Yes
<input type="radio" name="ironing" <?php if (isset($ironing) && $ironing=="No") echo "checked";?> value="No">No
<span class="error">* <?php echo $ironingErr;?></span>
<br>
Number Of Rooms:
<br>
<input type="text" name="Rooms">
<span class="error">* <?php echo $RoomErr;?></span>
<br>
Description of the House:
<br>
<textarea name="description" rows="10" cols="70"></textarea>
<span class="error">* <?php echo $descriptionErr;?></span>
<br>
<input type="submit" name="submit" value="Submit">
</form>
Quite simply after checking for errors and loading error message variables, you send the email without checking if any errors have been spotted.
So try adding some code before the email is sent to check for any found errors like this for example
First change this line to set the error variables to NULL
$nameErr = $lastNameErr = $emailErr = $ironingErr = $descriptionErr = $RoomErr = NULL;
And then wrap the email sending in a test like this
if (isset( $nameErr) || isset($lastNameErr) || isset($emailErr) ||
isset($ironingErr) || isset($descriptionErr) || isset($RoomErr) ) {
// You have an error
} else {
$to = "someemail#gmail.com"; // this is your Email address
$subject = "Order Sumbittion";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['description']. "\n\n" . "Number of Rooms: ". "\n\n" . $_POST['Rooms'] ."Ironing: " . $_POST['ironing'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['description']. "\n\n" . "Number of Rooms: " . "Number of Rooms: " . $_POST['Rooms'] ."Ironing: ". $_POST['ironing'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2);
// sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
header("Location: index.php");
}
This code works on my own website, the block of code used to email yourself and the user did not actually have an validation to check if any errors came up in your checks.
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$nameErr = $lastNameErr = $emailErr = $ironingErr = $descriptionErr = $RoomErr = "";
$first_name = $last_name = $email = $ironing = $description = $Rooms ="";
$error = false;
if(isset($_POST['submit']))
{
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$ironing = $_POST['ironing'];
$Rooms = $_POST['Rooms'];
$Description = $_POST['description'];
if (empty($_POST["first_name"])) {
$nameErr = "Name is required";
$error = true;
} else {
$name = test_input($_POST["first_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
$error = true;
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
$error = true;
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$error = true;
}
}
if (empty($_POST["description"])) {
$descriptionErr = "Description is required";
$error = true;
} else {
$description = test_input($_POST["description"]);
}
if (empty($_POST["Rooms"])) {
$RoomErr = "Room number is Required";
$error = true;
} else {
$Rooms = test_input($_POST["Rooms"]);
}
if (empty($_POST["ironing"])) {
$ironingErr = "Ironing is Required";
$error = true;
} else {
$ironing = test_input($_POST["ironing"]);
}
if ($error === false)
{
$to = "youremail#gmail.com"; // this is your Email address
$subject = "Order Sumbittion";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['description']. "\n\n" . "Number of Rooms: ". "\n\n" . $_POST['Rooms'] ."Ironing: " . $_POST['ironing'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['description']. "\n\n" . "Number of Rooms: " . "Number of Rooms: " . $_POST['Rooms'] ."Ironing: ". $_POST['ironing'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2);
// sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
header("Location: index.php");
}
}
// You can also use header('Location: thank_you.php'); to redirect to another page.
?>
<p><span class="error">* required field.</span></p>
<div class="col-md-9">
<form action="" method="post">
First Name: <input type="text" name="first_name">
<span class="error">* <?php echo $nameErr;?></span><br>
<br>
Last Name: <input type="text" name="last_name">
<span class="error">* <?php echo $lastNameErr;?></span><br>
Email:
<br>
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br>
Ironing?<br>
<input type="radio" name="ironing" <?php if (isset($ironing) && $ironing=="Yes") echo "checked";?> value="Yes">Yes
<input type="radio" name="ironing" <?php if (isset($ironing) && $ironing=="No") echo "checked";?> value="No">No
<span class="error">* <?php echo $ironingErr;?></span>
<br>
Number Of Rooms:
<br>
<input type="text" name="Rooms">
<span class="error">* <?php echo $RoomErr;?></span>
<br>
Description of the House:
<br>
<textarea name="description" rows="10" cols="70"></textarea>
<span class="error">* <?php echo $descriptionErr;?></span>
<br>
<input type="submit" name="submit" value="Submit">
</form>
If you don't want to refresh page, then you can use ajax call to send data on server to validate. Otherwise form will submit and page will refresh every time you slick submit.
And email is being sent every time weather data is valid or not, because there is no condition to check if data is valid. So use a variable and assign it 'false' and before sending check if its still true then send email.
}
First things first , the solution to your issue is that even you caught the error
if (empty($_POST["email"])) {
$emailErr = "Email is required";
}
you did not applied any check to make sure that script execution does not continue , for this you can add die(); also you can take a status variable as $status = 0; if you find any error just assign $status = 1 and before sending email check if($status == 0).
Now if you want to show error message without refreshing the page I would suggest to use jquery or any plugin such as https://validatejs.org/

Want PHP to validate before sending form to email

I am trying to create a form that will validate through php before submitting it to email, once the submit button has been pressed. I have been fooling around with the code and I am not skilled enough to figure it out. Currently, it will send the email whether the form has validated or not.
<?php
// define variables and set to empty values
$first_nameErr = $emailErr = $last_nameErr = $phone = $area_code = "";
$first_name = $email = $last_name = $message = $phone = $area_code = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["first_name"])) {
$first_nameErr = "First Name is required";
} else {
$first_name = test_input($_POST["first_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-']*$/",$first_name)) {
$first_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["last_name"])) {
$last_nameErr = "Last Name is required";
} else {
$last_name = test_input($_POST["last_name"]);
// check if e-mail address is well-formed
if (!preg_match("/^[a-zA-Z-']*$/",$last_name)) {
$last_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["area_code"])) {
$area_codeErr = "Area Code is required";
} else {
$area_code = test_input($_POST["area_code"]);
// check if e-mail address is well-formed
if (!preg_match("/^[0-9'-]*$/",$area_code)) {
$area_codeErr = "Only numbers allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^[0-9]*$/",$phone)) {
$phoneErr = "Only numbers and dashes allowed";
}
}
if (empty($_POST["message"])) {
$messageErr = "Brief Description is required";
} else {
$message = test_input($_POST["message"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($_POST['submit'])){
ob_start();
$to = "xyou1018#gmail.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$last_name = $_POST['last_name'];
$phone = $_POST['phone'];
$area_code = $_POST['area_code'];
$case_number = $_POST['case_number'];
$courthouse = $_POST['courthouse'];
$subject = "Strobach Law Firm, LLC. Form Submission";
$subject2 = "Strobach Law Firm, LLC. Form Received";
$message = "First Name:" . " " . $first_name . "\n\n" . "Last Name:" . " " . $last_name . "\n\n" . "Phone#:" . " " . $area_code . " " . $phone . "\n\n" . "Email:" . " " . $_POST['email'] . "\n\n" . "Courthouse" . " " . $courthouse . "\n\n" . "Case Number:" . " " . $case_number . "\n\n" . "wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "" . "\n\n" . "" . "\n" . "Phone # - " . "\n" . "Fax # - " . "\n" . "" . "\n" . "";
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
header('Location: ');
}
?>
<!DOCTYPE html>
<head>
<title>Contact
</title>
</head>
<body class="home">
<h1><u>Contact Information</u></h1>
<p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<h5>An * denotes a required field</h5>
*First name:
<br><input type="text" name="first_name" Placeholder="First Name" value="<?php echo $first_name;?>" />
<span class="error"><?php echo $first_nameErr;?></span>
<p>
*Last name:
<br><input type="text" name="last_name" Placeholder="Last Name" size="20" />
<span class="error"><?php echo $last_nameErr;?></span>
<p>
*Phone:
<br>
(<input type="text" name="area_code" Placeholder="xxx" size="1" />) <span class="error"><?php echo $area_codeErr;?></span> <input type="text" name="phone" Placeholder="xxxxxxx" size="7" />
<span class="error"><?php echo $phoneErr;?></span>
<p>
*Email:
<br><input type="" name="email" Placeholder="Email#Email.com" size="20" />
<span class="error"><?php echo $emailErr;?></span>
<p>
Courthouse:
<br><input type="text" name="courthouse" Placeholder="Courthouse" size="20" />
<p>
Case Number:
<br><input type="text" name="case_number" Placeholder="Case Number" size="20" />
<p>
*Brief Description:
<br>
<textarea name="message" Cols="40" rows="20"/></textarea>
<span class="error"><?php echo $messageErr;?></span>
<p>
<input type="submit" name="submit" value="Submit">
</form>
If you prefer to use a different method to Email us, Please choose from the following below:
<p>
In Email Correspondence please include:
<p>
Name
<br>
Phone Number(s)
<br>
Your Case number, if you know it
<br>
What courthouse your case is located in
<br>
A brief description of your case
<p>
<img src="img/gmail.jpg" alt="Gmail" height="21" width="28"> - Opens Gmail
<p>
<img src="img/ymail.jpg" alt="Ymail" height="25" width="24"> - Opens Yahoo Mail
<p>
<img src="img/aolmail.jpg" alt="AOL Mail" height="25" width="25"> - Opens AOL Mail
<p>
<img src="img/livemail.jpg" alt="Live Mail" height="21" width="32"> - Opens Live Mail
</body>
</html>

sending form info to email

I have a form that sends info to php doc. When testing, I submit and array displays but won't go to email address.
<?php require_once("/includes/fbcheader.php");
?>
<div class="comments">
<h3> We Welcome All Comments </h3>
<form action="/php/contact-send.php" method="post"
id="contact-form" class="form">
<p class="input-block">
<label for="form-name" >Name</label>
<input type="text" value name="name" id="form-name"
autofocus placeholder="Please enter name" required>
</p>
<p class="input-block">
<label for="form-email" >Email</label>
<input type="email" value name="email" id="form-email"
required placeholder="Please enter E-Address">
<input type="hidden" value name="age" id="age">
</p>
<p class="input-block">
<label for="form-subject" >Subject</label>
<input type="text" value name="subject" id="form-subject"
required placeholder="Please enter subject">
</p>
<p class="textarea-block">
<label for="form-message">Comment</label>
<textarea name="message" id="form-message"
cols="70" rows="10"></textarea>
</p>
<div class="clear"></div>
<input type="hidden" name="firstname" id="firstname">
<input type="submit" value="Send" id="form-submit">
<p class="hide" id="response"></p>
<div class="hide">
<label for="spam-check">Do not fill out this field</label>
<input name="spam-check" type="text" value id="spam-check">
</div>
</form>
</div>
</body>
</html>
This is the sending php execute code
<html>
<head>
<title>Contact-Send</title>
</head>
<body>
<?php
if(null!==($_POST["name"])) {
$name = $_POST["name"];
/* echo "Please enter 'Name'<br />"; */
} else {
$name = "";
}
if(null!==($email = $_POST["email"])) {
$email = $_POST["email"];
/* echo "Please enter 'E_Mail'<br />"; */
} else {
$email = "";
}
if(null!==($email = $_POST["subject"])) {
$form_email = $_POST["subject"];
/* echo "Please enter 'Subject'<br />"; */
} else {
$subject = "";
}
if(null!==($message = $_POST["message"])) {
$message = $_POST["message"];
/* echo "Please enter your message<br />"; */
} else {
$message = "";
}
/*echo "{$name}, {$email}, {$message}";*/
$email_from = '$Email';
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n".
"Here is the message:\n $message".
$to = "me#myaddress.com";
?>
<br>
<?php
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $form_email \r\n";
mail($to,$email_subject,$email_body,$headers);
header("thank-you.html");
?>
</body>
</html>
On submit I simply get the array displaying the content of the input fields
A quick look at your PHP code I see the following:
This: if(null!==($email = $_POST["email"])) will fail because you are running a check against nothing. it should be: if(null!==($_POST["email"])).
You have an undefined variable here: $email_from = '$Email'; this will simply output "$Email". It should be $email_from = $email; (as per your code). However you are simply re-assigning the variable here which you dont really need to be doing at all.
Your concatenating the $email_body and $to address.
You header("thank-you.html"); will fail because as per your code, output has already started here <?php (line 6).
You should be aiming for something closer to this for your contact-send.php:
<?php
if(null!==($_POST["name"])) {
$name = $_POST["name"];
/* echo "Please enter 'Name'<br />"; */
} else {
$name = "";
}
if(null!==($_POST["email"])) {
$email = $_POST["email"];
/* echo "Please enter 'E_Mail'<br />"; */
} else {
$email = "";
}
if(null!==($_POST["subject"])) {
$form_email = $_POST["subject"];
/* echo "Please enter 'Subject'<br />"; */
} else {
$subject = "";
}
if(null!==($_POST["message"])) {
$message = $_POST["message"];
/* echo "Please enter your message<br />"; */
} else {
$message = "";
}
/*echo "{$name}, {$email}, {$message}";*/
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n".
"Here is the message:\n $message";
$to = "me#myaddress.com";
$headers = "From: $email \r\n";
$headers .= "Reply-To: $email \r\n";
mail($to,$email_subject,$email_body,$headers);
header("Location: thank-you.html");
?>
Remember to set $to to your email address!

My php form is not checking if the email entered in my form is valid

There's a couple of things that I need some help on:
I have a function called isValid that is not checking if the emails entered in my form are valid?
How can i have my error messages display inside the form's text field?
Any help is greatly appreciated!
Below is my code:
<?php
//Set Variables to Empty String
$Email = " ";
$Subject = " ";
$Name = " ";
$Message = " ";
$error = " ";
if(isset($_POST['submit']) )
{
if (empty($_POST["Email"]))
{
$error = "** Enter a valid email";
}
else
{
$Email = isValid($_POST["Email"]);
}
if (empty($_POST["Subject"]))
{
$error = "** Enter a subject";
}
else
{
$Subject= test_input($_POST["Subject"]);
}
if (empty($_POST["Name"]))
{
$error = "** Enter your name";
}
else
{
$Name= test_input($_POST["Name"]);
}
if (empty($_POST["Message"]))
{
$error = "** Enter your message";
}
else
{
$Message= test_input($_POST["Message"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//isValid checks if email address is a valid one
function isValid($edata)
{
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]* [[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][ 0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $edata));
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p><label>From (Email):</label></p>
<input type="text" size="35" name="Email">
<span class="error"><?php echo $error;?></span>
<br><br>
<p><label>Subject:</label></p>
<input type="text" size="35" name="Subject">
<span class="error"><?php echo $error;?></span>
<br><br>
<p><label>Name:</label></p>
<input type="text" size="35" name="Name">
<span class="error"><?php echo $error;?></span>
<br><br>
<p><label>Message:</label></p>
<textarea type="text" cols="38" rows="6" name="Message"></textarea>
<span class="error"><?php echo $error;?></span>
<br><br>
<input type="submit" name="submit" value="submit">
<input type="reset" value="Reset">
</form>
<?php
if(empty($error))
{
// the email will be sent here
$to = "#gmail.com";
// the email subject
$subject = 'Message from XXXX website from: ' . $Name;
// the mail message
$msg .= "\r\nEmail: $Email";
$msg .= "\r\n\nSubject: $Subject";
$msg .= "\r\n\nName: $Name";
$msg .= "\r\n\nMessage: $Message";
mail($to, $subject, $msg, "From: $Email\r\nReply-To: $Email\r\nReturn-Path: $Email\r\n");
}
?>
<p>Thank you <b><?=$Name;?></b> for your message. Expect a response in 1 - 3 business days</p>
validate functions
<?php
$email_a = 'joe#example.com';
$email_b = 'bogus';
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_b) email address is considered valid.";
}
?>
for second question, change your code like this:
if (empty($_POST["Email"]))
{
$error['Email'] = "** Enter a valid email";
}
.
.
.
if (empty($_POST["Name"]))
{
$error['Name'] = "** Enter your name";
}
.
.
.
<input type="text" size="35" name="Email">
<span class="error"><?php echo $error['Email'];?></span>
<input type="text" size="35" name="Name">
<span class="error"><?php echo $error['Name'];?></span>

Contact form with required fields will not submit - using PHP validation [closed]

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.");
}

Categories