The below HTML and PHP code executes as expected in Google Chrome - enter the requested data into the form and press send, then a message is sent to an email address and the page is refreshed.
However, the same expected behaviour does not occur in Safari - once the 'send' button is clicked the user is brought to a blank white page (the email.php file).
Can anyone tell me why it does not do as expected in Safari?
HTML Code:
<form method="POST" id="contactForm" name="contactForm" class="contactForm" novalidate="novalidate" action="email.php" onsubmit="this.submit(); this.reset(); return false;">
<div class="row">
<!-- Name Input -->
<div class="col-md-1 col-sm-1">
<div class="form-group">
<label class="contact-text">Name:</label>
</div>
</div>
<div class="col-md-11 col-sm-11 contact-col">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name">
</div>
</div>
<!-- Email Input -->
<div class="col-md-1 col-sm-1">
<div class="form-group">
<label class="contact-text">Email:</label>
</div>
</div>
<div class="col-md-11 col-sm-11 contact-col">
<div class="form-group">
<input type="email" class="form-control" name="email" id="email">
</div>
</div>
<!-- Message Input -->
<div class="col-md-1 col-sm-1">
<div class="form-group">
<label class="contact-text">Message:</label>
</div>
</div>
<div class="col-md-11 col-sm-11 contact-col">
<div class="form-group">
<textarea class="form-control" name="message" id="message" cols="30" rows="6"></textarea>
</div>
</div>
</div>
</div>
</div>
<!-- Submit Button -->
<div class="col-md-8 col-sm-8 col-8 text-end">
<div class="form-group">
<button type="submit" class="btn btn-primary">Send</button>
<div class="submitting"></div>
</div>
</div>
</div>
</form>
PHP Code:
$errors = [];
$errorMessage = '';
if (!empty($_POST)) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if (empty($name)) {
$errors[] = 'Name is empty';
}
if (empty($email)) {
$errors[] = 'Email is empty';
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Email is invalid';
}
if (empty($message)) {
$errors[] = 'Message is empty';
}
if (empty($errors)) {
$toEmail = 'cillinlyons#outlook.com';
$emailSubject = 'New email from your contant form';
$headers = ['From' => $email, 'Reply-To' => $email, 'Content-type' => 'text/html; charset=iso-8859-1'];
$bodyParagraphs = ["Name: {$name}", "Email: {$email}", "Message:", $message];
$body = join('<br>', $bodyParagraphs);
if (mail($toEmail, $emailSubject, $body, $headers)) {
header('Location: https://cillinlyons.me');
} else {
$errorMessage = 'Oops, something went wrong. Please try again later';
}
} else {
$allErrors = join('<br/>', $errors);
$errorMessage = "<p style='color: red;'>{$allErrors}</p>";
}
}
?>
you need a name for your button to set it with php
<button type="submit" class="btn btn-primary" name="submit">Send</button>
and use array_push() to have all errors in a array ,
i used isset() for check the submit is clicked or not.
<?php
$errors = [];
$errorMessage = '';
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if (empty($name)) {
array_push($errors, 'Name is empty');
}
if (empty($email)) {
array_push($errors, 'Email is empty');
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
array_push($errors, 'Email is invalid');
}
if (empty($message)) {
array_push($errors, 'Message is empty');
}
if (empty($errors)) {
$toEmail = 'cillinlyons#outlook.com';
$emailSubject = 'New email from your contant form';
$headers = ['From' => $email, 'Reply-To' => $email, 'Content-type' => 'text/html; charset=iso-8859-1'];
$bodyParagraphs = ["Name: {$name}", "Email: {$email}", "Message:", $message];
$body = join('<br>', $bodyParagraphs);
if (mail($toEmail, $emailSubject, $body, $headers)) {
header('Location: https://cillinlyons.me');
} else {
$errorMessage = 'Oops, something went wrong. Please try again later';
}
} else {
foreach ($errors as $error)
echo "<p style='color: red;'>{$error}</p>";
}}
i tested this on safari and its working
Related
<!-- THIS IS USING GOOGLES reCaptcha V2 -->
<?php
if(isset($_POST['ContactButton'])) {
$url = "https://www.google.com/recaptcha/api/siteverify";
$privateKey = "##########################";
$response = file_get_contents($url."?secret=".$privateKey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data->success==true) {
$error = "";
$successMsg = "";
if ($_POST) {
if ($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$error .= "The email is invalid!<br>";
}
if (!$_POST['email']) {
$error .= "An email address is required!<br>";
}
if (!$_POST['subject']) {
$error .= "A subject is required!<br>";
}
if (!$_POST['body']) {
$error .= "Content in the body is required!<br>";
}
if ($error != "") {
$error = '<div class="alert alert-danger" role="alert"><strong>There is an error with your form!</strong><br>' . $error . '</div>';
} else {
$emailTo = 'contactform#########.com';
$subject = $_POST['subject'];
$body = $_POST['body'];
$headers = "From: ".$_POST['email'];
if (mail($emailTo, $subject, $body, $headers)) {
$successMsg = '<div class="alert alert-success" role="alert">The message has successfully been sent. We will contact you ASAP!</div>';
} else {
$error = '<div class="alert alert-danger" role="alert">There was a problem sending your message, please try again later!</div>';
}
}
}
} else {
$captchaFail = '<div class="alert alert-danger" role="alert"><strong>There is an error with your form!</strong><br>reCaptcha Verification Failed, Please Try Again.</div>';
}
}
?>
<div class="jumbotron" id="contact-us-co" style="display: none">
<p>Contact Us:
<br><br>
<form method="POST" class="container">
<h2 style="text-align:center;">***Contact Us***</h2>
<br>
<div id="error"><?php echo $successMsg ?><?php echo $error ?><?php echo $captchaFail ?></div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="inputSubject">Subject</label>
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject">
</div>
<label for="inputBody">Message</label>
<div class="form-group input-group">
<textarea class="form-control" aria-label="With textarea" placeholder="Body" name="body" id="body"></textarea>
</div>
<div class="g-recaptcha" data-sitekey="###################"></div>
<br>
<button type="submit" class="btn btn-primary" name="ContactButton" id="ContactButton">Submit</button>
</form> </p>
</div>
Solution #1 (not sure how to add this code)
code to prevent refresh:
document.getElementById('ContactButton').addEventListener('click', function(event) {
event.preventDefault();
}, false);
Solution #2
After form refresh reset back to the Contact Page: (I used onClick for behaviors)
Contact Us
It's a default html form behavior. If you want to send form data without page reloading you need to looking for AJAX (or AjaxForm plugin):
F.e:
jQuery AJAX submit form
I am stumped....
I have created a PHP form to gather some user information and email it to the site owner, after the form is submitted, the fields auto complete with a '1' I am assuming this means the field was true and submitted.
Does anyone have any suggestions on how to hide or remove the 1 after the form is submitted? I just want the form to be blank after submission. Here is the code, Sorry for the poor formatting and eye bleeding wall of code.
Thank you in advance for any help!
PHP Code
$errName = "";
$errcatBreed = "";
$errEmail = "";
$errMessage = "";
$result = "";
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$catBreed = $_POST['catBreed'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'PearTreeHill Contact Form';
$to = 'test#domain.com';
$subject = "New furbaby enquiry from $name";
$body ="From: $name\n Cat Breed: $catBreed\n E-Mail: $email\n Message:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if cat breed has been entered
if (!$_POST['catBreed']) {
$errcatBreed = 'Please enter either Ragdoll or British ShortHair';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
// RECAPTCHA
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
{
$secret = 'Private Key';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success)
{
$succMsg = 'Your contact request have submitted successfully.';
}
else
{
$errMsg = 'Robot verification failed, please try again.';
}
}
// If there are no errors, send the email
if (!$errName && !$errcatBreed && !$errEmail && !$errMessage) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again.</div>';
}
}
}
HTML Code
<!-- contact form -->
<section id="contactUs" class="bg">
<div class="container">
<div class="row">
<div class="col-lg-8 mx-auto">
<div class="text-center">
<h2 class="w3-tangerine">Contact Us</h2>
</div>
<!-- start of entry form -->
<form class="form-horizontal" role="form" method="post" action="index.php">
<!-- name entry -->
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars(isset($_POST['name'])); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<!-- cat breed selection -->
<div class="form-group">
<label for="catBreed" class="col-sm-2 control-label">Cat Breed</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="catBreed" name="catBreed" placeholder="'Ragdoll' or 'British ShortHair'" value="<?php echo htmlspecialchars(isset($_POST['catBreed'])); ?>">
<?php echo "<p class='text-danger'>$errcatBreed</p>";?>
</div>
</div>
<!-- email address entry -->
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-12">
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" value="<?php echo htmlspecialchars(isset($_POST['email'])); ?>">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
</div>
<!-- Body of message -->
<div class="form-group">
<label for="message" class="col-sm-2 control-label">Message</label>
<div class="col-sm-12">
<textarea class="form-control" rows="4" name="message" placeholder="Please enter any other information"><?php echo htmlspecialchars(isset($_POST['message']));?></textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<!-- reCAPTCHA -->
<div class="g-recaptcha" data-sitekey="Public Key" data-callback="recaptcha_callback"></div>
<!-- send button -->
<input disabled="disabled" id="submit" name="submit" type="submit" value="Send Message" class="btn btn-danger">
<label for="submit" class="col-sm-8 control-label">Please allow up to 48 hours for a response!</label>
</div>
</div>
<!-- entry alert -->
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</form>
</div>
</div>
</div>
<?php echo htmlspecialchars(isset($_POST['email'])); ?>
Here you display the result of isset() (TRUE or FALSE).
You should do :
<?php if ( isset($_POST['email']) ) echo htmlspecialchars($_POST['email']); ?>
And this for each field :-)
change
echo htmlspecialchars(isset($_POST['name']));
to
echo htmlspecialchars ($_POST['name'])
I mean remove isset();
I am receiving empty email from Submit form every day around the same time.
Form Code :
<div class="form">
<h4 class="h-light text-center">Submit a Query</h4>
<form class="form-horizontal" action="sendemail.php" method="post" id="contact_form">
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="name" placeholder="Name" class="form-control input-text" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label">E-Mail</label>
<div class="col-sm-10 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input name="email" placeholder="E-Mail Address" class="form-control input-text" type="email" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label">Phone #</label>
<div class="col-sm-10 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input name="phone" placeholder="(123)456-7890" class="form-control input-text" type="text" required>
</div>
</div>
</div>
<!-- Text area -->
<div class="form-group">
<label class="col-sm-2 control-label">Message</label>
<div class="col-sm-10 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea class="form-control input-text text-area" name="message" placeholder="Enter your massage for us here. We will get back to you." required></textarea>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><img src="media/home/captcha.png"></label>
<div class="col-sm-10">
<div class="input-group">
<div class="g-recaptcha" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"></div>
</div>
</div>
</div>
<!-- Success message -->
<div class="alert alert-success" role="alert" id="success_message">Success <i class="glyphicon glyphicon-thumbs-up"></i> Thanks for contacting us, we will get back to you shortly.</div>
<!-- Button -->
<div class="form-group">
<label class="col-sm-4 control-label"></label>
<div class="col-sm-8">
<button type="submit" class="input-btn" >Send <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</form>
sendemail.php Code:
<?php
/* These are the variable that tell the subject of the email and where the email will be sent.*/
$emailSubject = 'New query !';
$mailto = 'xxx#domain.in';
/* These will gather what the user has typed into the field. */
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
/* This takes the information and lines it up the way you want it to be sent in the email. */
$body = <<<EOD
<br><hr><br>
Name: $name <br>
Email Address: $email <br>
Phone Number: $phone <br>
Message: $message<br>
EOD;
$headers = "From:domain.in<xxx#domain.in>\r\n"; // This takes the email and displays it as who this email is from.
$headers .= "Content-type: text/html\r\n"; // This tells the server to turn the coding into the text.
//$success = mail($mailto, $emailSubject, $body, $headers); // This tells the server what to send.
if(mail($mailto, $emailSubject, $body, $headers))
{
echo "Your query has been submitted successfully. ";
echo 'Go Back';
}
else
{
echo "Failure";
}
?>
I have no idea what is going on, the code seems to be fine, but still i am receiving that empty email only with the field name like...
Name :
Email Address :
Phone Number :
Message :
But no information filled in it.
Thanks in advance.
Validate the input on the PHP side before you send the email. eg:
$valid = true;
$name = $_POST['name'];
if(empty($name))
{
echo('Please enter your name');
$valid = false;
}
// Repeat for other fields
if($valid)
{
// Send the email
}
I am not so good with PHP, please let me know if it correct.. Thank you
<?php
/* These are the variable that tell the subject of the email and where the email will be sent.*/
$emailSubject = 'New query!';
$mailto = 'xxx#domain.in';
/* These will gather what the user has typed into the fieled. */
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
/* This takes the information and lines it up the way you want it to be sent in the email. */
$body = <<<EOD
<br><hr><br>
Name: $name <br>
Email Address: $email <br>
Phone Number: $phone <br>
Message: $message<br>
EOD;
$headers = "From:domain.in<info#domain.in>\r\n"; // This takes the email and displays it as who this email is from.
$headers .= "Content-type: text/html\r\n"; // This tells the server to turn the coding into the text.
//$success = mail($mailto, $emailSubject, $body, $headers); // This tells the server what to send.
$valid = true;
$name = $_POST['name'];
if(empty($name))
{
echo('Please enter your name');
$valid = false;
}
$email = $_POST['email'];
if(empty($email))
{
echo('Please enter your email');
$valid = false;
}
$phone = $_POST['phone'];
if(empty($phone))
{
echo('Please enter your Phone number');
$valid = false;
}
$message = $_POST['message'];
if(empty($message))
{
echo('Please enter your message');
$valid = false;
}
if($valid)
{
if(mail($mailto, $emailSubject, $body, $headers))
{
echo "Your query has been submitted successfully. ";
echo 'Go Back';
}
}
else
{
echo "Failure";
}
i
?>
Should be working now?
$valid = true;
$name = $_POST['name'];
if(empty($name))
{
echo('Please enter your name');
$valid = false;
}
<br/>
$email = $_POST['email'];
if(empty($email))
{
echo('Please enter your email');
$valid = false;
}
<br/>
$phone = $_POST['phone'];
if(empty($phone))
{
echo('Please enter your Phone number');
$valid = false;
}
<br/>
$message = $_POST['message'];
if(empty($message))
{
echo('Please enter your message');
$valid = false;
}
<br/>
if($valid)
{
if(mail($mailto, $emailSubject, $body, $headers))
{
echo "Your query has been submitted successfully. ";
echo 'Go Back';
}
}
else
{
echo "Failure";
}
?>
Checking for whether $_Post is empty is the usual and logical way to go.
But for someone who is curious about why the same empty email is being sent to you everyday (usually it's some kind of bot) why not add the following fields in your message body so you know what's happening.
This way you learn how the web works better too.
For example
$ip = $_SERVER['REMOTE_ADDR']; // for IP address
$browser = $_SERVER['HTTP_USER_AGENT']; // get browser info
and you add above info to your message body so you know what's going on.
I just made my contact form to function, sort of. It has a few issues:
When the form is sent, it kicks you off the page, directs you to a blank page with the message: "Thank you etc". I would love to stay on the page, and just either get a box pop-up with the success message or just have it on the page. Either is fine :)
The error message doesn't show, it just puts you on a blank page.
The errMessages like "please fill in a valid e-mail" don't show. Probably because I removed the labels, but I would like to show that message IN the box rather than under it.
It's overriding my CSS! But that happens sometimes on my computer, one time I see lines other times I see boxes. So that issue might be somewhere else. However with the 'working form' it changes my last box.
This is what I meant with changing CSS on my boxes
PHP code:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'Demo Contact Form';
$to = 'denise#hetfulfilmentbedrijf.nl';
$subject = 'Message from Contact Demo';
$body = "From: $name\n Subject: $subject\n Number: $phone\n E-Mail: $email\n Message:\n $message";
//Check if name has been entered
if(!$_POST['name']) {
$errName = 'Vul alsjeblieft je naam in';
}
//Check if subject has been entered
if(!$_POST['subject']) {
$errName = 'Vul alsjeblieft een onderwerp in';
}
//Check if number has been entered
if(!$_POST['phone']) {
$errName = 'Vul alsjeblieft je nummer in';
}
//Check if e-mail is entered and valid
if(!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Vul alsjeblieft je e-mailadres in';
}
//Check if message has been entered
if(!$_POST['email']) {
$errMessage = 'Laat alsjeblieft een bericht achter';
}
// If no errors, send email
if (!$errName && !$errSubject && !$errPhone && !$errEmail && !$errMessage) {
if (mail ($to, $subject, $body, $from)) {
echo $result='<div class="alert alert-success">Thank You! I will be in touch</div>';
}
else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
HTML:
<form class="form-horizontal" role="form" method="post" action="partials/contactform.php">
<div class="form-group offset-top-45">
<textarea rows="11" cols="100" class="form-control" id="message" name="message" placeholder="Laat hier je bericht voor ons achter:"></textarea><?php echo htmlspecialchars($_POST['message']);?></textarea>
<span class="help-block" style="display: none;">Laat alsjeblieft een bericht achter</span>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
</div>
<div class="col-md-6">
<div class="row offset-top-10">
<div class="pull-right">
<img height="60" width="100" src="/images/stamp.png" alt="stamp">
</div>
</div>
<div class="row offset-top-10" style="padding-right:20px; padding-left:10px">
<form role="form" id="feedbackForm">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Hoe heet je?" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<span class="help-block" style="display: none;">Vul alsjeblieft je naam in</span>
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
<div class="form-group">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Wat is het onderwerp?" value="<?php echo htmlspecialchars($_POST['subject']); ?>">
<span class="help-block" style="display: none;">Vul alsjeblieft een onderwerpin</span>
<?php echo "<p class='text-danger'>$errSubject</p>";?>
</div>
<div class="form-group">
<input type="text" class="form-control" id="phone" name="phone" placeholder="Op welk nummer kunnen wij jou bereiken?" value="<?php echo htmlspecialchars($_POST['phone']); ?>">
<span class="help-block" style="display: none;">Vul alsjeblieft je nummer in</span>
<?php echo "<p class='text-danger'>$errPhone</p>";?>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Wat is je e-mailadres?">
<span class="help-block" style="display: none;">Vul alsjeblieft je e-mail in</span>
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
<div class="form-group">
<div class="col-md-12 text-right">
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary btn-s">
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</div>
</div>
</form>
Help is much appreciated!
Full script it should work without any problems
<?php
$result = "";
$errors = ""; //use to count errors
//Error message variables
$errName = "";
$errSubject = "";
$errEmail = "";
$errMessage = "";
//message variables
$name = "";
$subject = "";
$phone = "";
$email = "";
$message = "";
$to = "denise#hetfulfilmentbedrijf.nl";
if (isset($_POST['submit'])) {
//check if name has been entered
if (empty($_POST['name'])) {
$errName = "Vul alsjeblieft je naam in";
$errors++;
} else {
$name = UserInput($_POST['name']);
}
////Check if subject has been entered
if (empty($_POST['subject'])) {
$errSubject = "Vul alsjeblieft een onderwerp in";
$errors++;
} else {
$Subject = UserInput($_POST['subject']);
}
//check if email entered
if (empty($_POST['email'])) {
$errEmail = "Laat alsjeblieft een bericht achter";
$errors++;
} else {
$email = UserInput($_POST['email']);
// check if email is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$errEmail = "Vul alsjeblieft je e-mailadres in";
$errors++;
}
}
if (empty($_POST['phone'])) {
$errPhone = "Vul alsjeblieft je nummer in";
$errors++;
} else {
$phone = UserInput($_POST['phone']);
// check if email is numbers
if (!is_numeric($phone)) {
$errPhone = "enter numbers only";
$errors++;
}
}
//check message
if (empty($_POST['message'])) {
$errMessage = "Laat alsjeblieft een bericht achter";
} else {
$message = UserInput($_POST['message']);
}
if ($errors > 0) {
// we have errors do not send email
$result = "<div class=\"alert alert-danger\">Sorry there was an error sending your message. Please fix " . $errors . " errors on the form </div>";
} else {
//no errors set email headers and send email
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: <' . $email . '>' . "\r\n";
$body = "<p> New email from $name";
$body .= "<p> Phone : $phone</p>";
$body .= "<p> Email : $email<p>";
$body .= "<p>Message : $message</p>";
if (mail($email, $subject, $msg, $header)) {
$result = "<div class=\"alert alert-success\">Thank You! I will be in touch</div>";
$_POST = array(); //clear the form aftter sendig
} else {
$result = "<div class=\"alert alert-danger\">Sorry there was an error sending your message. Please try again later</div>";
}
}
}
//sanitise use input
function UserInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form class="form-horizontal" role="form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<div class="col-md-12 text-right">
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary btn-s">
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</div>
</div>
<div class="form-group offset-top-45">
<textarea rows="11" cols="100" class="form-control" id="message" name="message" placeholder="Laat hier je bericht voor ons achter:"></textarea><?php if(!empty($_POST['message'])){echo $_POST['message'];}?></textarea>
<?php echo "<p class=\"text-danger\">".$errMessage."</p>";?>
</div>
</div>
<div class="col-md-6">
<div class="row offset-top-10">
<div class="pull-right">
<img height="60" width="100" src="/images/stamp.png" alt="stamp">
</div>
</div>
<div class="row offset-top-10" style="padding-right:20px; padding-left:10px">
<form role="form" id="feedbackForm">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Hoe heet je?" <?php if(!empty($_POST['name'])){echo "value=\"".$_POST['name']."\"";}?>>
<?php echo "<p class=\"text-danger\">".$errName."</p>";?>
</div>
<div class="form-group">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Wat is het onderwerp?" <?php if(!empty($_POST['Subject'])){echo "value=\"".$_POST['Subject']."\"";}?>>
<?php echo "<p class=\"text-danger\">".$errSubject."</p>";?>
</div>
<div class="form-group">
<input type="text" class="form-control" id="phone" name="phone" placeholder="Op welk nummer kunnen wij jou bereiken?" <?php if(!empty($_POST['phone'])){echo "value=\"".$_POST['phone']."\"";}?>>
<?php echo "<p class=\"text-danger\">".$errPhone."</p>";?>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Wat is je e-mailadres?">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
</form>
Let me know if you have any question or need any help.
my web form work fine, except
if user submit the form with 1 or more field missing
user will see error message and all the input/message gone.
user will have to type the message again
1) How to keep the message so user don't have to type again?
2) is my web form secure from spammer?
my web form
http://www.jewelryindonesia.com/contact.php
my form code:
<?php
// check for a successful form post
if (isset($_GET['s'])) echo "<div class=\"alert alert-success\">".$_GET['s']."</div>";
// check for a form error
elseif (isset($_GET['e'])) echo "<div class=\"alert alert-danger\">".$_GET['e']."</div>";
?>
<form role="form" method="POST" action="contact-form-submission.php">
<div class="row">
<div class="form-group col-lg-4">
<label for="input1">Name</label>
<input type="text" name="contact_name" class="form-control" id="input1">
</div>
<div class="form-group col-lg-4">
<label for="input2">Email Address</label>
<input type="email" name="contact_email" class="form-control" id="input2">
</div>
<div class="form-group col-lg-4">
<label for="input3">Phone Number/WhatsApp</label>
<input type="phone" name="contact_phone" class="form-control" id="input3">
</div>
<div class="clearfix"></div>
<div class="form-group col-lg-12">
<label for="input4">Message</label>
<textarea name="contact_message" class="form-control" rows="6" id="input4"></textarea>
</div>
<div class="form-group col-lg-12">
<input type="hidden" name="save" value="contact">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
my php:
<?php
// check for form submission - if it doesn't exist then send back to contact form
if (!isset($_POST['save']) || $_POST['save'] != 'contact') {
header('Location: contact.php'); exit;
}
// get the posted data
$name = $_POST['contact_name'];
$email_address = $_POST['contact_email'];
$phone = $_POST['contact_phone'];
$message = $_POST['contact_message'];
// check that a name was entered
if (empty($name))
$error = 'You must enter your name.';
// check that an email address was entered
elseif (empty($email_address))
$error = 'You must enter your email address.';
// check for a valid email address
elseif (!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $email_address))
$error = 'You must enter a valid email address.';
// check that a phone number was entered
if (empty($phone))
$error = 'You must enter your phone number.';
// check that a message was entered
elseif (empty($message))
$error = 'You must enter a message.';
// check if an error was found - if there was, send the user back to the form
if (isset($error)) {
header('Location: contact.php?e='.urlencode($error)); exit;
}
$headers = "From: $email_address\r\n";
$headers .= "Reply-To: $email_address\r\n";
// write the email content
$email_content = "Name: $name\n";
$email_content .= "Email Address: $email_address\n";
$email_content .= "Phone Number: $phone\n";
$email_content .= "Message:\n\n$message";
// send the email
//ENTER YOUR INFORMATION BELOW FOR THE FORM TO WORK!
mail ('xxxx#gmail.com', 'Jewelryxxx.com Online Form', $email_content, $headers);
// send the user back to the form
header('Location:jewelry-indonesia-thankyou.html?s='.urlencode('Your Message Has Been Sent ! Thank you for your message.')); exit;
?>
To avoid user don't have to type again when your script jump into error validation, you can store $_POST field to a variable, then call again that variable on html field value.
Web form spammer can be avoided by placing capcha and more validation input, as mentioned above simply can be ussing isset.
isset($_POST['keterangan']) for example
!isset() and $_POST[var]==""; same meaning
EDIT all proccess on 1 page code contact.php
<?php
$name = $_POST['contact_name'];
$email_address = $_POST['contact_email'];
$phone = $_POST['contact_phone'];
$message = $_POST['contact_message'];
if ($name=="" || $email_address="" || $phone=="" || $message==""){
if ($_POST['save']=="contact"){
echo "semua field harus diisi untuk melanjutkan";
}
}else{
// check that a name was entered
if (empty($name))
$error = 'You must enter your name.';
// check that an email address was entered
elseif (!isset($email_address))
$error = 'You must enter your email address.';
// check for a valid email address
elseif (preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email_address))
$error = 'You must enter a valid email address.';
// check that a phone number was entered
if (empty($phone))
$error = 'You must enter your phone number.';
// check that a message was entered
elseif (empty($message))
$error = 'You must enter a message.';
// check if an error was found - if there was, send the user back to the form
if (isset($error)) {
echo "<div class=\"alert alert-danger\">".$error."</div>";
}else{
$headers = "From: $email_address\r\n";
$headers .= "Reply-To: $email_address\r\n";
$email_content = "Name: $name\n";
$email_content .= "Email Address: $email_address\n";
$email_content .= "Phone Number: $phone\n";
$email_content .= "Message:\n\n$message";
mail ('xxxx#gmail.com', 'Jewelryxxx.com Online Form', $email_content, $headers);
// send the user back to the form
echo "<div class=\"alert alert-success\">Your Message Has Been Sent ! Thank you for your message.</div>";
}
}
echo '<form role="form" method="POST" action="contact.php">
<div class="row">
<div class="form-group col-lg-4">
<label for="input1">Name</label>
<input type="text" name="contact_name" class="form-control" id="input1" value="'.$name.'">
</div>
<div class="form-group col-lg-4">
<label for="input2">Email Address</label>
<input type="email" name="contact_email" class="form-control" id="input2" value="'.$email_address.'">
</div>
<div class="form-group col-lg-4">
<label for="input3">Phone Number/WhatsApp</label>
<input type="phone" name="contact_phone" class="form-control" id="input3" value="'.$phone.'">
</div>
<div class="clearfix"></div>
<div class="form-group col-lg-12">
<label for="input4">Message</label>
<textarea name="contact_message" class="form-control" rows="6" id="input4">'.$message.'</textarea>
</div>
<div class="form-group col-lg-12">
<input type="hidden" name="save" value="contact">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>';
?>