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/
Related
I am trying to create a form that checks and validates name, email. But I can't see any error messages. I don't know a lot of PHP, can't say that I even know the basics.
Here is the code:
<iframe name="formDestination" class="nnn"></iframe>
<div class="container33">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" class="thwid" method="post" target="formDestination">
<label for="fname">Full Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your full name..." value="<?php echo $name;?>"><span class="error">* <?php echo $nameErr;?></span>
<label for="email">Your E-mail</label>
<input type="text" id="email" name="email" placeholder="Your E-mail adress..."> <span class="error">* <?php echo $emailErr;?></span>
<label for="message">Your message</label>
<textarea id="message" name="message" placeholder="Write your message here / the reason why you want to contact us " ></textarea>
<input type="submit" name="submit" value="Submit">
</form>
</div>
<?php
if(isset($_POST['submit'])){
$to = "myemail#cencored.com";
$from = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2);
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
} ?>
<?php
$nameErr = $emailErr = "";
$name = $email = $comment = "";
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["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}?>
Move the form HTML code below all of the PHP code otherwise your error variables such as $emailErr won't be displayed as they are not defined before they are used.
Re-positioned code blocks in their proper places. Also deleted unneeded codes.
Try:
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($_POST['submit'])){
$emailErr = "";
$name = $email = $comment = "";
$nameErr = "";
if (empty($_POST["fullname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["fullname"]);
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["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if( trim( $emailErr ) == "" AND trim( $nameErr ) == "" ) {
$to = "2myemail#cencored.com";
$from = $_POST['email'];
$first_name = $_POST['fullname'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2);
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
}
}?>
<style>.error { color:red; } </style>
<!-- <iframe name="formDestination" class="nnn"></iframe> -->
<div class="container33">
<form action="" class="thwid" method="post">
<label for="fname">Full Name</label>
<input type="text" id="fname" name="fullname" placeholder="Your full name..." value="<?php echo #$name;?>"><span class="error">* <?php echo #$nameErr;?></span>
<label for="email">Your E-mail</label>
<input type="text" id="email" name="email" placeholder="Your E-mail adress..."> <span class="error">* <?php echo #$emailErr;?></span>
<label for="message">Your message</label>
<textarea id="message" name="message" placeholder="Write your message here / the reason why you want to contact us " ></textarea>
<input type="submit" name="submit" value="Submit">
</form>
</div>
<?php
$nameErr = $emailErr = "";
$name = $email = $comment = "";
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["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}?>
<div class="container33">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" class="thwid" method="post" target="">
<label for="fname">Full Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your full name..." value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br>
<label for="email">Your E-mail</label>
<input type="text" id="email" name="email" placeholder="Your E-mail adress...">
<span class="error">* <?php echo $emailErr;?></span>
<br>
<label for="message">Your message</label>
<textarea id="message" name="message" placeholder="" ></textarea>
<input type="submit" name="submit" value="Submit">
</form>
</div>
Try this.
<?php
$nameErr = $emailErr = "";
$name = $email = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["firstname"]) && $_POST["firstname"] != "") {
$name = test_input($_POST["firstname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
echo $nameErr;
}
} else {
$nameErr = "Name is required";
echo $nameErr;
}
if (isset($_POST["email"]) && $_POST["email"] != '') {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
echo $emailErr;
} else {
$emailErr = "Email is required";
echo $emailErr;
}
if (isset($_POST["comment"]) && $_POST["comment"] != '') {
echo $comment;
$comment = test_input($_POST["comment"]);
} else {
$comment = "";
echo $comment;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}?>
You need to echo the value if you get any error.
Tip : Always use isset to check if the value is set or not. Also do the same in your email function.
So I've made myself a little contact form with php, css, and html. But when I try to add a email validation it still sends the email and doesn't change the style of the input to red (Like I would like it to). Another issue I'm having is the button redirecting to the top of the page (which I do not want it to do). Last I can I make the input keep the text rather than remove it once submitted
HTML:
<div id="contact">
<div class="container">
<form id="contact-form" method="post">
<h1>Contact Form</h1>
<fieldset>
<input placeholder="Your Name" type="text" name="name" required>
</fieldset>
<fieldset>
<input placeholder="Your Email Address" type="email" name="email" id="email-input" required>
</fieldset>
<fieldset>
<input placeholder="Your Phone Number (optional)" type="tel" name="phone" required>
</fieldset>
<fieldset>
<input placeholder="Your Web Site (optional)" type="url" name="site" required>
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." name="message" required></textarea>
</fieldset>
<fieldset>
<button type="submit" id="contact-submit" name="submit">Submit</button>
</fieldset>
</form>
</div>
</div>
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$visitors_site = $_POST['site'];
$message = $_POST['message'];
$email_from = 'mattmowen1#gmail.com';
$email_subject = 'New Contact Submission';
$to = 'mattmowen1#gmail.com';
$headers = "From:" . $email;
$headers = "Contact Submission From: " . $email;
$message1 = "Name: " . $name;
$message2 = "\n\nEmail: " . $email;
$message3 = "\n\nPhone: " . $phone;
$message4 = "\n\nTheir Site: " . $visitors_site;
$message5 = "\n\nMessage: " . $message;
$email_body = $message1 . $message2 . $message3 . $message4 . $message5;
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
mail($to, $email_subject, $email_body,$headers);
} else {
echo "<style>#email-input {color:red}</style";
}
?>
Try this for email validation in php
<?php
if (isset($_POST) && !empty($_POST)) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$visitors_site = $_POST['site'];
$message = $_POST['message'];
$email_from = 'mattmowen1#gmail.com';
$email_subject = 'New Contact Submission';
$to = 'mattmowen1#gmail.com';
$headers = "From:" . $email;
$headers = "Contact Submission From: " . $email;
$message1 = "Name: " . $name;
$message2 = "\n\nEmail: " . $email;
$message3 = "\n\nPhone: " . $phone;
$message4 = "\n\nTheir Site: " . $visitors_site;
$message5 = "\n\nMessage: " . $message;
$email_body = $message1 . $message2 . $message3 . $message4 . $message5;
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
mail($to, $email_subject, $email_body,$headers);
} else {
echo "<style>#email-input {color:red}</style>";
}
}
?>
As per our chat conversation. I am adding jquery ajax function according to your form requirement.
You need to create new file email.php and put your php code into this separate php file
<script>
var url = 'email.php';
$.ajax({
url : url,
type : "POST",
dataType : "JSON",
data : $('#contact-form').serialize(),
success : function(response) {
if (response.error == 0) { // success
$('#contact-form')[0].reset();
alert('Form submitted successfully. We will contact you asap.');
} else { // error
$('#email-input').css('color', 'red');//in case of email error
alert('ERROR MESSAGE');//form is invalid
}
}
})
</script>
To handle JSON request you need to send JSON object in response. So change you php code snippet like this:
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
mail($to, $email_subject, $email_body,$headers);
exit(json_encode(array('error' => 0)));
} else {
exit(json_encode(array('error' => 1)));
}
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>
This code works and works well although I know there are definitely some redundancies and better ways to do things. For one, instead of using form action=mypage.php, I have all the php with all my html code. When I tried to have it all in mypage.php, none of the variables would be found in $_POST. Though isset would result to true on $_POST. So... weird, and screw it, I put it in with the html. I was trying with WAMP, but wouldn't work on the server either.
Another issue, refresh of the page after submission will send another email as well, which might be resolved if I solve the form action issue above.
How's my validation? Anything recommended to improve the process or security?
<h1><div class="titleWrapper"><div class="titleContact">Contact</div></div></h1>
<div class="contact">
<ul class="contactColumn">
<li>
<div class="fields">
<form method='POST'>
<input type="text" name="name" placeholder="Your Name" maxlength="50">
<input type="text" name="email" placeholder="Your Email" maxlength="80">
<textarea name ="message" placeholder="Your Message" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your Message'" maxlength="2000"></textarea>
<input type="checkbox" name="copy" style="display: inline-block;float:left"><span style="float:left;padding:17px 0 0 5px">Send me a copy</span>
<input type="submit" name="submit" value="Submit">
</form>
</div>
</li>
</ul>
<ul class="contactColumn">
<div class="rightSide">
<p>
Still have questions?
</p>
<p>
Need more information?
</p>
<p>
Feel free to contact us!
</p>
</div>
</ul>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed in your name";
}
}
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["message"])) {
$comment = "";
} else {
$comment = test_input($_POST["message"]);
}
if (empty($nameErr) && empty($emailErr)){
$to = "myemail#email.com";
$subject = "Contact form submission";
$subject2 = "Copy of your contact form";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $name . "\n\n" . $_POST['message'];
$headers = "From:" . $email;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
if (isset($_POST['copy'])) {
mail($email,$subject2,$message2,$headers2); // sends a copy of the message to the sender
}
echo "<div class='errorMessageWrapper'><div class='errorMessage'><div style='color:#333'>
Thank you for contacting us " .
$name .
". We will be in touch shortly. </div></div>";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
if (!empty($nameErr)) {
echo "<div class='errorMessageWrapper'><div class='errorMessage'><li style='list-style-type: circle;'>" . $nameErr . "</li></div></div>";
}
if (!empty($emailErr)) {
echo "<div class='errorMessageWrapper'><div class='errorMessage'><li style='list-style-type: circle;'>" . $emailErr . "</li></div></div>";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</div>
I was thinking to make the send email simpler with less code i would suggest PHPMailer it is less code and easier to use.
Take a look at the documentation for PHPMailer at: PHPMAILER DOCUMENTATION
PHPMailer should make it easier to read if you understand PHPMailer, and very simple to write.
HERE IS A EXAMPLE:
<?php
require_once "vendor/autoload.php";
$mail = new PHPMailer;
$mail->From = "from#yourdomain.com";
$mail->FromName = "Full Name";
$mail->addAddress("recipient1#example.com", "Recipient Name");
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";
if(!$mail->send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
}
Here is a link for the the sending emails with PHPMailer: Link
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'];