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
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
so I been breaking my head over this, I am pretty new so sorry if I said something wrong. So I got hosting, installed wordpress on it, and I put my html on it, it cointains conctact form written in html and it has separate php file with process. It kindda works, if i test it, it will send me an email, but I put header('Location: ../front-page.php'); and I get white page with error line, I am pretty sure there is no error cuz well if you go to website, it uses that line and it works just fine, problem is only after submitting form. I am adding a code and putting php in Javascript. Also if possible some extra related questions, is it possible when it redirects to front page also add alert table with success message? And now when I get message, I do not see the one who wrote it email, and its pretty essential, also would be nice to fix . Thank you guys very much!
<?php
// define variables and set to empty values
$name_error = $email_error = $message_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_error = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $message_error == '' and $url_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'ignas.levinskas#mail.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message)){
header('Location: ../front-page.php');
$name = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
<form id="contactform" method="post" action="http://li-designs.com/wp-content/themes/vcs-starter/assets/app.php" >
<input name="name" type="text" class="feedback-input" placeholder="Name" required/>
<span class="error"><?= $name_error ?></span>
<input name="email" type="text" class="feedback-input" placeholder="Email" required/>
<span class="error"><?= $email_error ?></span>
<textarea name="message" type="text" value="<?= $message ?>" class="feedback-input" placeholder="Message" ></textarea>
<span class="error"><?= $message_error ?></span>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Send</button>
</form>
Can anyone help me stop blank emails from being sent each time the page is viewed?
Here is the code I am using.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = "";
$name = $email = $gender = $comment = "";
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";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Comment is required";
} else {
$comment = test_input($_POST["comment"]);
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = "Please leave a comment.";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//create the body of the email
$body = "Name: {$_POST['name']}
\n\nEmail: {$_POST['email']}
\n\nComments: {$_POST['comment']}";
$body = wordwrap($body, 70);
// The mail function
mail('email#email.com', 'Contact Us Submission', $body, "From: {$_POST['email']}");
?>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" class="text" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br>
Email: <input type="text" name="email" class="text" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br>
Comment: <textarea name="comment" rows="3" cols="20"><?php echo $comment;?></textarea>
<span class="error">* <?php echo $commentErr;?></span><br>
<input type="submit" name="submit" value="Submit" class="submit">
<?php
//if everything is ok, print the message:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($name && $email && $comment) {
echo "<p>Thank you, <b>$name</b>, for contacting us.</p>
<p> We will email you back at <i>$email</i> in a couple days.</p>\n";
} else { //missing form value.
echo '<p class="error">Please go back and fill out the form again.</p>';
return false;
}
}
?>
</form>
Put all of your form logic inside of your if ($_SERVER["REQUEST_METHOD"] == "POST") { statement. Not just the validation:
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";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Comment is required";
} else {
$comment = test_input($_POST["comment"]);
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = "Please leave a comment.";
}
}
//create the body of the email
$body = "Name: {$_POST['name']}
\n\nEmail: {$_POST['email']}
\n\nComments: {$_POST['comment']}";
$body = wordwrap($body, 70);
// The mail function
mail('email#email.com', 'Contact Us Submission', $body, "From: {$_POST['email']}");
}
FYI, you are wide open to header injections. That's something you should address before publishing this code to production.
I am hoping that someone can help me with this PHP Script. It sends the email perfectly, although the validation doesn't work. This script is also not stripping HTML tags from the email when sent. This makes me worry that my sanitizeString function is not working properly and am open to xss. My user group will not have Java support...hence trying to use PHP.
Here is the PHP Code:
<?php
//Strip Tags and white Space from all input with this function
function sanitizeString($value){
$value = strip_tags($value);
$value = trim($value);
$value = escapeshellcmd($value);
$value = htmlentities($value);
return $value;
}
$send = $_POST[send];
//Email validation
if (filter_var($from, FILTER_VALIDATE_EMAIL)) {
$email_error = true;
$error_message[] = "Please use a valid email format: name#domain.com";
}
if($send == 1){$email_sent = true; $step_1 = "complete";}
else{$email_sent = false; $step_1 = "complete";}
if($email_sent === true) {
$from = sanitizeString($_POST['from']);
$to = sanitizeString($_POST['to']);
$name = sanitizeString($_POST['name']);
$title = sanitizeString($_POST['title']);
$company = sanitizeString($_POST['company']);
$phone = sanitizeString($_POST['phone']);
$subject = sanitizeString($_POST['subject']);
$message = sanitizeString($_POST['message']);
// define variables and initialize with empty values
$nameErr = $addressErr = $emailErr = $messageErr = $phoneErr = "";
$name = $address = $email = $message = $phone = "";
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["phone"])) {
$phoneErr = "Please enter a phone number.";
}
else {
$phone = $_POST["phone"];
}
if (empty($_POST["message"])) {
$messageErr = "Cannot leave message box blank.";
}
else {
$message = $_POST["message"];
}
}
//select the correct to address - This hides my email addresses from the source. Would love a better solution if you have one...
switch ($to) {
case "1":
$to = "Contact1#example.com";
break;
case "2":
$to = "Contact2#example.com";
break;
default:
$to = "Contact1#example.com";
break;}
if($message_error !== true && $email_error !== true){
$email_headers = "From:".$from."\nMIME-Version: 1.0 \nContent-type: text/html; charset=iso-8859-1";
$message_send = "<h3>".$name."<br>".$title."<br>".$company."<br>".$phone."<br>".$from."</h3><hr><h4>".$subject."</h4>".$message;
if (mail($to, $subject, $message_send, $email_headers)) {$error_message = "Thank you, your email is on the way!";}
else {$error_message = "There seems to be a problem!";}}
}
?>
For simplicity and the fact that I don't need HTML support, which I seem to get with every post asking for PHP help, here are my input fields. Yes before you comment on the input fields, I use css and I will be placing them in the right area of the page. :) Not trying to be rude, just trying to prevent suggestions outside of the topic stated above...
<form action="<?php ($_SERVER["PHP_SELF"]);?>" method="post">
<input name="name" placeholder="Name*" type="text" class="text"/><span class="error"><?php echo $nameErr;?></span>
<input type="text" placeholder="Title" name="title" size="50"/>
<input type="text" placeholder="Company" name="company" size="50" />
<input name="phone" placeholder="Phone*" type="tel" size="10" maxlength="10" value="<?php echo htmlspecialchars($phone);?>"/><span class="error" style="color:#990000"><?php echo $phoneErr;?></span>
<input name="from" placeholder="Email*" type="email" class="text" value="<?php echo htmlspecialchars($email);?>"><span class="error"><?php echo $emailErr;?>
<select name="to" size="1">
<option value="1">Contact1</option>
<option value="2">Contact2</option>
</select>
<input type="text" name="subject" placeholder="Subject" size="50" />
<textarea cols="50" rows="4" name="message" placeholder="Type your message here."></textarea>
<input type="hidden" name="send" value="1" /><input type="submit" value="Send" name="email_1" />
</form>
You are sanitizing here:
//note, moved the setting to "" before sanitizing
// define variables and initialize with empty values
$nameErr = $addressErr = $emailErr = $messageErr = $phoneErr = "";
$name = $address = $email = $message = $phone = "";
$from = sanitizeString($_POST['from']);
$to = sanitizeString($_POST['to']);
$name = sanitizeString($_POST['name']);
$title = sanitizeString($_POST['title']);
$company = sanitizeString($_POST['company']);
$phone = sanitizeString($_POST['phone']);
$subject = sanitizeString($_POST['subject']);
$message = sanitizeString($_POST['message']);
But then just assigning the variables here to the $_POST (not to the sanitized variable):
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please enter your name.";
}
else { // the else is not necessary; $name is already assigned if not empty.
$name = $_POST["name"];
}
if (empty($_POST["email"])) {
$emailErr = "Please enter your email.";
}
else { // the else is not necessary; $email is already assigned if not empty.
$email = $_POST["email"];
}
...
etc...
Change the last bit to reference your sanitized variables, like:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($name)) { // replaced $_POST['name'] with just $name
$nameErr = "Please enter your name.";
}
if (empty($email)) { // replaced $_POST['email'] with just $email
$emailErr = "Please enter your email.";
}
...
etc...
Edit- Update
To make sure the form was submitted, you should check your "submit" button.
(I would change the name from email_1 to submitted, for clarity).
So that in your HTML you have a submit button:
<input type="submit" name="submitted" value="true" >
Then, add something like this to your validation code:
if (!isset($_POST['submitted'])){
$formErr ="The form was not submitted";
exit(); // this line is optional to the line above it
}
The validation literally says: "If the submitted field is not set, then throw an error";