I am facing an issue, I have successfully validated the input and required fields in my form. But if the user Submits the form, no matter if the fields are empty; it shows the error message with fields but also send the empty email.
I believe there is just a simple tweak that needs to be done. But I am lost. Please look into the below code I have:
<?php
$nameErr = $snameErr = $emailErr = $ownerNameErr = $ownerNatErr = $genderErr = $websiteErr = "";
$name = $sname = $regAddress = $email = $gender = $comment = $ownerName = $ownerNat = $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";
}
}
if (empty($_POST["sname"]))
{$snameErr = "Company Second Name is required";}
else
{
$sname = test_input($_POST["sname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$sname))
{
$snameErr = "Only letters and white space allowed";
}
}
extract($_POST);
$to="example#example.com";
$subject="Subject";
$body="<table width='100%' cellspacing='10' cellpadding='0'>
<tr>
<td style='color:blue;font-weight:bold;margin-left:500px;font-size:20px;' colspan='3'>My Form</td>
</tr>
<tr>
<td>Name</td>
<td>:</td>
<td>$name</td>
</tr>
<tr>
<td>Second Choice</td>
<td>:</td>
<td>$sname</td>
</tr>
</table>";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: MySite '."\r\n";
/*$headers .= 'Reply-To:'."$textfield5"."\r\n";*/
if(mail($to,$subject,$body,$headers))
{
$msg = "Thank you for contacting us. We will get back to you soon.";
/*$msg= "Successfully Sent";*/
}
else
{
$msg= "msg not sent";
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
HTML Part
<span class="error">* <?php echo $ownerNatErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
input type="submit" name="submit" value="Submit Information">
Any help/Suggestion is highly appreciated.
Regards.
Your validation is correct and I assume it does what you want, however: you do not prevent the mail() function from running if the validation fails.
You could do this:
if ($valid) {
if (mail(...) {
...
} else {
...
}
}
This $valid variable sou should set to true by default and in the if statement, where you set the error messages, you should the variable to false.
This way the mail function would be called if the input is valid only.
Cheers.
You check the parameters for errors and set some error messages but your code calls mail anyway, even if you found an error.
You might want to add some conditions:
if($snameErr === '' && $nameErr === '' ...) {
// call mail here, check whether it was successful and
// tell the user about it
} else {
// show error message or something else
}
By the way, I guess your code is vulnerable because you use extract($_POST). An attacker might inject arbitrary variables and can therefore bypass your checks.
Related
Hi everyone and thanks for your time!
Although it's the first time that I try PHP, I've been making a PHP Form and so far I've been able to make it validate the fields, and also that the form doesn't send anything if the fields are empty.
Now... The fields "Name" and "Email" have validation filters...
"Name" doesn't allow more than "letters and white spaces" and "Email" doesn't allow an "invalid Email format".
Example:
Name: Rob3rt... it has a number
Email: anything... isn't an Email address
Subject and Message have no validation filters...
The problem is, that if I fill up all fields, the form sends the Email, even if the information written on "Name" and "Email" doesn't agree with their validation filters...
Q: How can I hold the form from sending an Email, until all fields have the correct information inside?
Here's the code:
// This is the validation code //
<?php
// define variables and set to empty values
$nameErr = $emailErr = $commentErr = $subjectErr = "";
$name = $email = $comment = $subject = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "<h5>Name is required</h5>";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "<h5>Only letters and white space allowed</h5>";
}
}
if (empty($_POST["email"])) {
$emailErr = "<h5>Email is required</h5>";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "<h5>Invalid email format</h5>";
}
}
if (empty($_POST["comment"])) {
$commentErr = "<h5>Message is required</h5>";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["subject"])) {
$subjectErr = "<h5>Subject is required</h5>";
} else {
$subject = test_input($_POST["subject"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form>
Form comes here
</form>
// This is the sending code... I think the problem is here... //
<?php
if($_POST['name']!="" && $_POST['email']!="" && $_POST['comment']!="" && $_POST['subject']!="") {
$to = "myemail#whatever.com";
$email = "From: " . $email . "\r\n";
$subject = "" . $subject . "\r\n";
$comment = "" . $comment . "\r\n";
mail($to,$subject,$comment,$email);
echo "good";
}
else {
"bad";
}
?>
It is not working, because you never check if an error occurred, you are only checking if the fields are not empty before you send the mail.
The simplest way to fix it is replacing
if($_POST['name']!="" && $_POST['email']!="" && $_POST['comment']!="" && $_POST['subject']!="") {
with
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $nameErr === '' && $emailErr === '' && $commentErr === '' && $subjectErr === '') {
There is no no need to check for empty fields again, you have already done it before, so you just need to check if you are POSTing the form and if all errors are empty.
Some advice on how to generally improve your code:
1) Do not handle the HTTP POST in two positions (once above the form and once below). Merge it together in one PHP code block.
2) At least make sure that the user can't re-submit a successful form by reloading the site. After a successful submit, redirect the page. Something like this:
mail($to,$subject,$comment,$email);
header('Location:' . $_SERVER['REQUEST_URI'] . '?status=ok');
exit();
3) separate your HTML from your PHP or you will end up with a huge file which gets hard to maintain. Put your HTML form in a separate file and include it.
Although imho the nicest solution for a form is to sanitize in in JavaScript, submit it via AJAX (with angular, react, jQuery, whatever), handle it (and sanitize the data again) in PHP, send a 4xx HTTP header on error and return the error messages as a JSON object, which you then use in JavaScript.
I have 3 fields validating correctly. The submissions post to a text file correctly. However, they post - - (as I have in the code to separate each section) even when the submit button is clicked without filling in the information. There should not be any empty information with just 2 - - printed to the text file without filling in the 3 fields first. How can I fix that? Sorry for the inconvenience, I answered my own question in another post and was able to fix the problem. Thank you for your time.
Here is my code
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['website'])) {
if(empty($_POST['name'])) {
$errors[] = "Name is required";
} else{
$name = htmlentities($_POST['name']);
$name = test_input($_POST['name']);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errors[] = "Only letters and white space allowed for the name";
}
}
if(empty($_POST['email'])) {
$errors[] = "Please provide your Email address.";
} else if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ===
false){
$errors[] = "Your Email is not valid.";
} else {
$email = htmlentities($email);
}
if(empty($_POST['website'])) {
$errors[] = "Please provide your company URL.";
} else{
$website = htmlentities($_POST['website']);
$website = test_input($_POST['website']);
if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$errors[] = "Please provide a valid URL for your company.";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$data = $name . " - " . $email . " - " . $website;
$file = "textfile.txt";
if($_POST){
file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
}
?>
In the html I have
<?php
if(empty($errors) === false){
?>
<ul>
<?php
foreach($errors as $error){
echo "<li>",$error,"</li>";
}
?>
</ul>
<?php
}else{
if(isset($name, $email, $website)){
echo "<b>Thank you for your submission.</b>";
}
}
?>
</div>
<div class="wrapper w3-round-xlarge">
<div class="formtitle w3-round-xlarge">Thank you for filling in all fields below
</div>
<div class="formwrapper w3-round-xlarge">
<form name="mobile" id="mobile" method="post" enctype="multipart/form-data" action="data.php"><br/>
etc. (the html document starts and ends correctly. Thank you for your help.
If all three inputs are required them, place required into the html input.
<Input name="email" required />
Do this for each input. This will not allow for the form to be processed until all fields are filed.
Sorry to inconvenience anyone for taking the time to read my post. I was able to fix the problem simply by removing the following from the php code above my html and changing the following
if($_POST){
file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
}
to ...
<?php
}else{
if(isset($name, $email, $website)){
file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
echo "<b>Your submission has been sent.</b>";
}
and adding it to the html div area
I am trying to validate my RSVP form using only PHP. The user should receive an error message when the form is incomplete. I am trying to avoid the use of jQuery.
I am using this tutorial:
http://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/
The form is functioning fine but I haven't been able to get the error messages to display at all. I am using Wordpress and I want the form to appear at the footer of every page; not sure if this complicates matters. Here is my code:
<?php
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message) {
global $response;
if ($type == "success") {
$response = "<div class='success'>{$message}</div>";
} else {
$response = "<div class='error'>{$message}</div>";
}
}
//response messages
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//variables defined for messages
$email = $_POST["rsvp_email"];
$name = $_POST["rsvp_name"];
$attend = $_POST["rsvp_attend"];
$number = $_POST["rsvp_number"];
//variables defined for message to admin
$to = get_option('admin_email'); //sending to wordpress admin email
$subject = "Just Kidding You Foo";
$headers = "From: $email\n";
$message = "$name $attend.\n RSVPs $number of people";
//conditional statements used for form validation
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
my_contact_form_generate_response("error", $email_invalid);
} else { //email is valid
//validate presence of name and message
if(empty($name) || empty($attend) || empty($number)) {
my_contact_form_generate_response("error", $missing_content);
} else { //ready to go!
$sent = wp_mail($to,$subject,$message,$headers);
if($sent) {
my_contact_form_generate_response("success", $message_sent); //message sent!
} else {
my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
}
}
}
?>
<div id="page-rsvp">
<h1>RSVP</h1>
<div id="respond">
<?php echo $response; ?>
<form action="<?php the_permalink(); ?>" method="post">
<!--Name here-->
<div class="rsvp-full"><label for="rsvp_name"><input type="text" name="rsvp_name" value="Your name"></label></div>
<div class="rsvp-full"><label for="rsvp_email"><input type="text" name="rsvp_email" value="Your email"></label></div>
<!--status of attendance-->
<div class="rsvp-full">
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="accepts">Accepts</div>
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="declines">Declines</div>
</div>
<!--number of guests attending-->
<div class="rsvp-full"><input type="number" name="rsvp_number" min="1" max="5">Total number of guests attending</div>
<div id="submit-button" class="rsvp-full"><input id="submit-button" type="submit"></div>
</form>
</div>
</div>
TIA!!!
I'm not that familiar with WP, but if I understand correctly, I believe you're trying to ensure all the fields are filled out.
Check your brackets! You need to be sure your curly brackets are opening and closing where you want them to. Otherwise the output of the page won't display. I write in all my braces because I'm not smart enough to be sure I know where they start and stop. I've taken the liberty of editing them into your question. I believe there was one missing at the end.
Once I fixed the brackets and removed functions my computer didn't have, it worked fine.
Tip 0: Try turning error reporting on for this script - error_reporting(E_ALL); at the top of this script. I always do for development.
Tip 1: use the placeholder attribute instead of value for things like "your name".
Tip 2: make sure the $_POST vars are set. I would do this by checking if they're set and then setting them to '' if they aren't; something like this:
//variables defined for messages
// you could do it like this:
if (isset($_POST["rsvp_email"])) {
$email = $_POST["rsvp_email"];
} else {
$email = '';
}
// or like this:
$name = '';
if (isset($_POST["rsvp_name"])) {
$name = $_POST["rsvp_name"];
}
// or even using a ternary operator:
$attend = isset($_POST["rsvp_attend"]) ? $_POST["rsvp_attend"] : '';
//but this will trigger a "Notice" error if the post var isn't set.
$number = $_POST["rsvp_number"];
So I created a custom contact form in WordPress, using PHP. The form sends, and I am receiving emails. The problem I'm having is that once you hit submit, it goes to a post page, and doesn't stay on the original page.
I've tried using a session and header location (didn't work)
I also tried putting this in my action"<?php echo $_SERVER['PHP_SELF']; ?>", doesn't work either. (mail just doesn't send it and sends me to 404 page.
So I'm a little stuck, as to fix this problem. Normally I would have no problems if this was a static web page, but because I'm using WordPress, this task seems to be more troublesome.
Here is a link to the website http://www.indianpointresort.ca/
Here is the php validation:
<?php
/*session_start();
if(!isset($_SESSION['afaisfjisjfijfjiwaefjawsefijef'])){
$url = 'http://www.indianpointresort.ca/';
header("Location:home.php?url=$url");
}*/
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
echo "$name | $email | $phone | $subject | $message";
if(isset($_POST['submit'])){
$boolValidationOK = 1;
$strValidationMessage = "";
//validate first name
//validate last name
if(strlen($name)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper first and last name </br>";
}
//email validation:
$emailValidate = validate_email( $email );// calls the function below to validate the email addy
if(!$emailValidate ){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in proper email address </br>";
}
//validate phone
$phone = checkPhoneNumber($phone);
if(!$phone){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill proper phone number </br>";
}
//validate subject
if(strlen($subject)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper subject description </br>";
}
//validate description
if(strlen($message)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper message </br>";
}
if($boolValidationOK == 1){
//$strValidationMessage = "SUCCESS";
//MAIL SECURITY !!!!!!!
// WE MUST VALIDATE AGAINST EMAIL INJECTIONS; THE SPAMMERS BEST WEAPON
$badStrings = array("Content-Type:",
"MIME-Version:",
"Content-Transfer-Encoding:",
"bcc:",
"cc:");
foreach($_POST as $k => $v){// change to $_POST if your form was method="post"
foreach($badStrings as $v2){
if(strpos($v, $v2) !== false){
// In case of spam, all actions taken here
//header("HTTP/1.0 403 Forbidden");
echo "<script>document.location =\"http://www.bermuda-triangle.org/\" </script>";
exit; // stop all further PHP scripting, so mail will not be sent.
}
}
}
$ip = $_SERVER['REMOTE_ADDR'];
//echo $ip;
/* Spammer List: IP's that have spammed you before ***********/
$spams = array (
"static.16.86.46.78.clients.your-server.de",
"87.101.244.8",
"144.229.34.5",
"89.248.168.70",
"reserve.cableplus.com.cn",
"94.102.60.182",
"194.8.75.145",
"194.8.75.50",
"194.8.75.62",
"194.170.32.252"
//"S0106004005289027.ed.shawcable.net" Phil's IP as test
); // array of evil spammers
foreach ($spams as $site) {// Redirect known spammers
$pattern = "/$site/i";
if (preg_match ($pattern, $ip)) {
// whatever you want to do for the spammer
echo "logging spam activity..";
exit();
}
}
$to = "";
//$subject = " Indian Point";
// compose headers
$headers = "From: Indian Point Resort.\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "X-Mailer: PHP/".phpversion();
$message = wordwrap($message, 70);
// send email
mail($to, $subject, $message, $headers);
}
}//end of submit
//validate phone number
function checkPhoneNumber($number){
$number = str_replace("-", "", $number);
$number = str_replace(".", "", $number);
$number = str_replace(" ", "", $number);
$number = str_replace(",", "", $number);
$number = str_replace("(", "", $number);
$number = str_replace(")", "", $number);
if((strlen($number) != 10) || (!is_numeric($number))){
return false;
}else{
return $number;
}
}
//email validation
function validate_email( $senderemail ){ // this is a function; it receives info and returns a value.
$email = trim( $senderemail ); # removes whitespace
if(!empty($email) ):
// validate email address syntax
if( preg_match('/^[a-z0-9\_\.]+#[a-z0-9\-]+\.[a-z]+\.?[a-z]{1,4}$/i', $email, $match) ):
return strtolower($match[0]); # valid!
endif;
endif;
return false; # NOT valid!
}
?>
Here is the form:
<div id="msgForm" class=" msgForm five columns">
<h4>Questions?</h4>
<h5>Send us a message!</h5>
<form id="contactForm" name="contactForm" method="post" action="<?php the_permalink(); ?>">
<p><input type="text" name="name" value="<?php echo $name; ?>" placeholder="name*"/></p>
<p><input type="email" name="email" placeholder="E-mail*"/></p>
<p><input type="text" name="phone" placeholder="Phone #*"/></p>
<p><input type="text" name="subject" placeholder="subject*"/></p>
<p><textarea name="message" placeholder="Message*"></textarea></p>
<p><input type="submit" name="submit" placeholder="Submit"/></p>
<div class="error">
<?php
if($strValidationMessage){
echo $strValidationMessage;
}
?>
</div>
</form>
</div><!--end of form-->
Well, to start off I would remove that gmail account from your info (just to be safe).
Secondly I would advise you to use the sendmail scripts provided by Wordpress.
There are plugins like gravityforms which allow you to make a form and decide all these options without making a static form, nor a new template file for that matter.
You can only change to which page the form will redirect after the refresh (the action will decide that)
If you want it to stay on the same page you can put the page itself in the action and on top put an if statement like
if(isset($_POST['submit'])){
//validation, sendmail, and possibly errors here
}
else{
//show the form
}
anyway, a refreshing webform is as standard as it gets. It's just how it submits things. The only way you could prevent a page is by using jquery or javascript like so: (give your submit an id)
$('#submit').on("click", function(e){
//this prevents any submit functionality (like refresh)
e.preventDefault();
//custom code to get values here and put them in the sendmail function like so:
var message = $('$message').text();
}
Try ajax form submission. And add the insert query in a separate file.
I need to add one more field in the php email form below, but I don't know much about php.
I need to add a field for a phone number, and I can see that the new field needs to be entered into the function build_message near the end of the formemail.php script. I've added $phone, but no luck in getting it to work and I get no error messages.
The html for the whole form is
<form action="formemail.php" method="post">
<input type="text" name="name" value="name" id="name" size="35" />
etc.... and the phone field is:
<input type="text" name="phone" value="Phone" id="phone" size="35" /> </form>`
The php form:
$my_email = "senttoemail#gmail.com";
$continue = "/";
$errors = array();
if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}}
function recursive_array_check_header($element_value)
{
global $set;
if(!is_array($element_value)){if(preg_match("/(%0A|%0D|\n+|\r+)(content-type:|to:|cc:|bcc:)/i",$element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_header($value);}
}
}
recursive_array_check_header($_REQUEST);
if($set){$errors[] = "You cannot send an email header";}
unset($set);
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
{
if(preg_match("/(%0A|%0D|\n+|\r+|:)/i",$_REQUEST['email'])){$errors[] = "Email address may not contain a new line or a colon";}
$_REQUEST['email'] = trim($_REQUEST['email']);
if(substr_count($_REQUEST['email'],"#") != 1 || stristr($_REQUEST['email']," ")){$errors[] = "Email address is invalid";}else{$exploded_email = explode("#",$_REQUEST['email']);if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){$errors[] = "Email address is invalid";}else{if(substr_count($exploded_email[1],".") == 0){$errors[] = "Email address is invalid";}else{$exploded_domain = explode(".",$exploded_email[1]);if(in_array("",$exploded_domain)){$errors[] = "Email address is invalid";}else{foreach($exploded_domain as $value){if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){$errors[] = "Email address is invalid"; break;}}}}}}
}
if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";}
function recursive_array_check_blank($element_value)
{
global $set;
if(!is_array($element_value)){if(!empty($element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_blank($value);}
}
}
recursive_array_check_blank($_REQUEST);
if(!$set){$errors[] = "You cannot send a blank form";}
unset($set);
if(count($errors)){foreach($errors as $value){print "$value<br>";} exit;}
if(!defined("PHP_EOL")){define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");}
function build_message($request_input){if(!isset($message_output)){$message_output ="";}if(!is_array($request_input)){$message_output = $request_input;}else{foreach($request_input as $key => $value){if(!empty($value)){if(!is_numeric($key)){$message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;}else{$message_output .= build_message($value).", ";}}}}return rtrim($message_output,", ");}
$message = build_message($_REQUEST);
$message = stripslashes($message);
// $phone = stripslashes($phone);
$subject = "Webmail";
$headers = "From: " . $_REQUEST['email'];
mail($my_email,$subject,$message,//$phone, $headers);
Where did you get this script from? The $message variable is the body of your email and it looks like it's created by running the build_message function. You can get rid of your $phone variable as it appears as if the script automatically finds all the form fields by looking through the input fields ($_REQUEST). I ask where you got the form from to see if there's some sort of simple documentation about this and maybe you need to add something to your form that tells the script what fields to add to your message