I have a message that I need to prepopulate for a textarea. This message can be edited by users.
If there is a form validation error, the message appears to be duplicated each time that an error occurs.
<textarea name="comments" rows="20" style="width:99%;"><?=$fields['comments']?>TEXT
HERE</textarea>
I don't believe that this is an error due to the validation, but rather the field saving the content and adding it to the existing prepopulated message.
Is there a way that I can load the message and have users edit it without duplication?
I can provide any code necessary. I am currently using this code for validation:
https://github.com/benkeen/php_validation
<?php
session_start();
$_SESSION['name'] = $_POST['name'];
$_SESSION['senders_email'] = $_POST['senders_email'];
$_SESSION['address'] = $_POST['address'];
$_SESSION['city'] = $_POST['city'];
$_SESSION['state'] = $_POST['state'];
$_SESSION['comments'] = $_POST['comments'];
//e-mail message text
$body=<<<_MSG_
Hello,
$comments
Sincerely,
$name
$address
$city
$state
_MSG_;
$text = strip_tags($body);
$errors = array();
$fields = array();
$success_message = "";
if (isset($_POST['submit']))
{
require_once("validation.php");
$rules = array(); // stores the validation rules
$rules[] = "required,name,Your <em>Name</em> is required.";
$rules[] = "required,senders_email,Your <em>E-mail</em> is required.";
$rules[] = "valid_email,senders_email,Please enter a valid e-mail address.";
$rules[] = "required,address,Your <em>Address</em> is required.";
$errors = validateFields($_POST, $rules);
if (!empty($errors))
{
$fields = $_POST;
}
// no errors! redirect the user to the thankyou page (or whatever)
else
{
mail($to,$subject,$text,$headers);
header( "Location: thanks.php" );
}
}
?>
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 have a php form that i'm trying to make required fields for but I cannot seem to get it to work right and I know its something i'm missing. I just need to make the form require $name $bank $email and $phone.
<?php
/* Set e-mail recipient */
$myemail = "email#email.com";
/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Enter your name");
$bank = check_input($_POST['bank'], "Enter your name");
$email = check_input($_POST['email']);
$phone = check_input($_POST['phone']);
$headphones = check_input($_POST['headphones']);
$subject = "Allied Affiliated Funding - Bose Landing Page Form Submission";
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* Let's prepare the message for the e-mail */
$message = "Hello!
Your contact form has been submitted by:
Name: $name
Bank: $bank
E-mail: $email
Phone: $phone
Head Phones: $headphones
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
if($_POST['headphones'] == Yes){
header("Location: landing1/thank-you-bose.html");
}
else {
header("Location: landing1/thank-you.html");
}
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
I have looked at several different tutorials on how to complete this but none of the solutions seem to be working.
I think your problem is at this line
if($_POST['headphones'] == Yes){
It needs to be
if($_POST['headphones'] == "Yes"){
You dont have a variable named Yes so i think you want to check if the content of headphones is "yes".
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.
So I recently made a basic site for a family members small company. I included a mail form, for enquiries etc.
here is the code i use:
<?php
function check_input($data){ // SANITIZE USER STRING INPUT
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = check_input($_POST['name']);
$surname = check_input($_POST['surname']);
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$comments = check_input($_POST['message']);
$message = "From: $name $surname
Email: $email
Telephone: $telephone
--------------------------------------------------------------
Comments: $comments
";
mail("#############.com","Website Enquiry from www.#######.co.uk",$message,"From: webserver");
?>
now when I try it, it works absoloutely fine. However I have noticed sometimes it is realllllly slow and so we have been receiving blank emails through the form (the user input data is not present), so it appears someone has attempted to use it and given up perhaps because it is taking too long?
I am assuming this is to do with the mail server rather than php mail. But I wanted to see if anyone could highlight potential issues that I could take to the company hosting for her?
many thanks,
check if name and email fields are entered and then proceed with mail function..this reduces getting blank emails.
<?php
if (isset($_POST['name']) && isset($_POST['email'])) //check if name and email fields are entered and then proceed with mail function
{
//process the data and send mail.
}
else
{
echo "Error missing name or email field.please enter";
}
?>
Alternatively you can also use array_key_exists()
<?php
if (array_key_exists("name", $_POST) && $_POST["name"] != "" && array_key_exists("email", $_POST) && $_POST["email"] != "")
//check if name and email fields are entered and then proceed with mail function
{
//process the data and send mail.
}
else
{
echo "Error missing name or email field.please enter";
}
?>
Actually you are not checking if someone fill the form empty that's why you are getting blank fields
<?php
function check_input($data){ // SANITIZE USER STRING INPUT
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($data))
{
$name = check_input($_POST['name']);
$surname = check_input($_POST['surname']);
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$comments = check_input($_POST['message']);
$message = "From: $name $surname
Email: $email
Telephone: $telephone
--------------------------------------------------------------
Comments: $comments
";
mail("#############.com","Website Enquiry from www.#######.co.uk",$message,"From: webserver");
}
?>