I have an html input form as well as a php email script that takes these values on the same page.
The problem is that before I submit any data into the forms I get a blank email because my php script is not waiting for the user input.
I don'y wan't to use another page for my email script because I don't want to pass variables through GET and I don't know how to implement sessions yet.
Thanks and here is my code
<div id = "center">
<form action="post.php" name="emailform" method="post">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="message">
<input type="submit" value="Send Email">
</form>
</div>
<?php
if (!isset($_POST['submit'])) {
echo 'you have hit the submit button';
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$email_from = 'trustyclient#yoursite.com';
$email_subject = "Message from client";
$email_body = "Message from: $visitor_email \n \n Message:$message";
$to = "myemail#myemail.com";
$headers = "from:adam\r\n";
mail($to,$email_subject,$email_body,$headers);
} else {
echo 'You have not hit the submit button yet';
}
?>
First, give your submit button a name, like 'submit' (because you've already referenced that name in the PHP). Example:
<input type="submit" name="submit" value="Send Email">
Now you can actually use $_POST['submit'] in your code.
Then another tweak:
When you state if (!isset($_POST['submit'])) {, the following code runs if the submit button has not been pressed, because of the !. To fix, just remove the !, making it:
if (isset($_POST['submit'])) {
! tells the if statement to evaluate to true if the following expression, here isset($_POST['submit']), evaluates to false. Therefore ! means "if the opposite".
NB: Also, the concept that the PHP runs when the submit button is pressed is slightly off. The submit button triggers that page to load a different page (or the same page). The PHP code runs only once when the page loads.
Try this.
<div id = "center">
<form action="post.php" name="emailform" method="post">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="message">
<input type="submit" value="Send Email">
</form>
</div>
<?php
if (isset($_POST['submit'])) {
echo 'you have hit the submit button';
if (empty(trim($_POST['name'])) || empty(trim($_POST['email'])) || empty(trim($_POST['message']))) {
echo 'Some fields are empty.';
} else {
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$email_from = 'trustyclient#yoursite.com';
$email_subject = "Message from client";
$email_body = "Message from: $visitor_email \n \n Message:$message";
$to = "myemail#myemail.com";
$headers = "from:adam\r\n";
mail($to,$email_subject,$email_body,$headers);
}
} else {
echo 'You have not hit the submit button yet';
}
?>
Related
I have a problem with my code. I'm creating a contact form. I don't know about php, I'm learning and I have a problem. What's wrong with this code, every time I refresh the page an email was sent and you I see "Confirm form resubmission" information which is annoying. Can you help me solve these problems?
<?php
$show = "";
if(isset($_POST['submit'])){
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'].".\n\n"."Sent from contact form.";
$to = "Test <test#justtest.com>";
$headers = "From: ".$name."<".$email.">";
mail($to,$subject,$message,$headers);
$show = "<p class='success'>Your message was sent.</p>";
}
}
?>
<form action="index.php" method="POST" class="form">
<input type="text" name="name" placeholder="Name" required>
<input type="email" name="email" placeholder="Your email" required>
<input type="text" name="subject" placeholder="Subject">
<textarea name="message" rows="5" placeholder="Message" required></textarea>
<button type="submit" name="submit">Send</button>
<?php echo $show;?>
</form>
Generally the approach to solve the "Confirm form resubmission" is to redirect after processing a form post. So instead of just re-rendering the page, you'd do something like this:
if(isset($_POST['submit'])){
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
// the rest of the code you already have, then...
header("Location:index.html");
die();
}
}
You can of course replace "index.html" with any page you like, in this case I imagine it would be the current page.
What this does is instruct the browser to not render the current response (if there even is anything in the response) but instead to issue a new GET request to the specified page in the header. So if the user then later refreshes that page, they're only refreshing the GET request and not re-submitting the form.
Edit: You can also still show your message to the user:
$show = "<p class='success'>Your message was sent.</p>";
What you would do in this case is not show the message where you currently have it, but instead include it as a separate operation on the page invoked by a query string parameter. So you might have something like this:
$show = "";
if(isset($_GET['sent'])){
$show = "<p class='success'>Your message was sent.</p>";
}
if(isset($_POST['submit'])){
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
// unchanged code not shown here for brevity
mail($to,$subject,$message,$headers);
header("Location:index.html?sent=true");
die();
}
}
And later in the page you can output the message like you already do:
<?php echo $show;?>
The way this message gets triggered is by the query string paramter used in the redirect:
header("Location:index.html?sent=true");
Which means that technically any time somebody goes to your page with sent=true manually they would see the message without actually sending the email. But if users are tinkering like that then the behavior they get is the behavior they should expect. If you're keen on preventing this otherwise inoccuous tinkering then you could also store a flag in $_SESSION rather than in the query string. That's up to you.
when you submit the form, a post request is sent, and so by reloading the page, the same form is been resubmitted over and over.
In order to solve this, you just need to redirect the user to the same page, instead of returning the page itself, so you need to add
header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";); // or paste here the url of the page where the form is located
die();
after
mail($to,$subject,$message,$headers);
So you ends up with this:
<?php
$show = "";
if(isset($_POST['submit'])){
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'].".\n\n"."Sent from contact form.";
$to = "Test <test#justtest.com>";
$headers = "From: ".$name."<".$email.">";
mail($to,$subject,$message,$headers);
header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";); // or paste here the url of the page where the form is located
die();
$show = "<p class='success'>Your message was sent.</p>";
}
}
?>
<form action="index.php" method="POST" class="form">
<input type="text" name="name" placeholder="Name" required>
<input type="email" name="email" placeholder="Your email" required>
<input type="text" name="subject" placeholder="Subject">
<textarea name="message" rows="5" placeholder="Message" required></textarea>
<button type="submit" name="submit">Send</button>
<?php echo $show;?>
</form>
php html
In order to keep the <p class='success'>Your message was sent.</p> you can use GET parameters:
<?php
$show = "";
if(isset($_POST['submit'])){
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'].".\n\n"."Sent from contact form.";
$to = "Test <test#justtest.com>";
$headers = "From: ".$name."<".$email.">";
mail($to,$subject,$message,$headers);
header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]?redirect=true";); // or paste here the url of the page where the form is located
die();
} else if(isset($_GET['redirect'])){
$show = "<p class='success'>Your message was sent.</p>";
}
}
?>
<form action="index.php" method="POST" class="form">
<input type="text" name="name" placeholder="Name" required>
<input type="email" name="email" placeholder="Your email" required>
<input type="text" name="subject" placeholder="Subject">
<textarea name="message" rows="5" placeholder="Message" required></textarea>
<button type="submit" name="submit">Send</button>
<?php echo $show;?>
</form>
php html
Newb here, sorry in advance. I want to check for errors in a simple html form. I want the form to email me the customers information. I have my contact.php and errorcheck.php uploaded to my hosting provider. i actually made a working script contactform.php. (working) So I have a clue that my host can process the php code, but my errorcheck.php script is not working. Can anyone check my errorcheck.php script and see what may be causing the problem. all I want errorcheck.php to do so far, is display the error in the web address bar, just so I know that its working. Thanks in advance for helping a newb. I hope I explained my self and code well enough.
contactform.php (working script will connect and send me an email of form information)
errorcheck.php (will not connect or check the form for errors, I want to display the error in web address bar)
contact.php (this is the html form)
errorcheck.php code below
<?php
if (isset($_POST['submit'])) {
$first = $_POST['name'];
$mail = $_POST['mail'];
$subject = $_POST['subject'];
$message = $_POST['message'];
//check if inputs are empty
if (empty($first) || empty($mail) || empty($subject) || empty($message)) {
header("Location:contact.php?signup=empty");
exit();
} else {
if (!preg_match("/^[a-zA-Z]*$/", $first)) {
header("Location:contact.php?signup=char");
exit();
} else {
//check if email is valid
if (!fiter_var($mail, FILTER_VALIDATE_EMAIL)) {
header("Location:contact.php?signup=invalid-email");
exit();
} else {
header("Location:contact.php?signup=signup=success");
}
}
}
}
(html code will connect to contactform.php but not errorcheck.php)
contact.php form code is below
<form class="contact-form" action="contactform.php" method="post">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Full name..">
<label for="mail">Email Address</label>
<input type="text" name="mail" placeholder="Your E-Mail..">
<label for="subject">Phone Number</label>
<input type="text" name="subject" placeholder="Phone Number..">
<label for="message">Message</label>
<textarea name="message" placeholder="Message.."></textarea>
<input type="submit" value="submit" name="submit"></input>
</form>
contactform.php code is below
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$mailFrom = $_POST['mail'];
$message = $_POST['message'];
$mailTo = "sales#screenrunners.com";
$headers = "From: ".$mailFrom;
$txt = "You have received and e-mail from ".$name.".\n\n".$message;
mail($mailTo, $subject, $txt, $headers);
header("Location: contact.php?mailsend");
}
?>
I have a form for which i am trying to validate the email address. If the email address is incorrect i want a value of "Please type a valid email address." to be returned into the "email" input box on the form. What am i doing wrong? No validation is taking place. I receive the form information at my email and once submitted the user is sent to the "Thank you" page, but no validation. I can put anything in the "email" input and the form will submit.
<form action="../php/contact.php" method="post">
<p>First Name:</p>
<input class="box_style" type="text" name="first_name" required maxlength="20" />
<p>Last Name:</p>
<input class="box_style" type="text" name="last_name" required maxlength="25" />
<p>Email:</p>
<input class="box_style" type="text" name="email" required maxlength="50" />
<p>Contact Number (optional):</p>
<input class="box_style" type="text" name="contact_number" maxlength="12" />
<p>How did you find us?</p>
<select class="box_style" name="how" required>
<option value="choose">Select...</option>
<option value="referal">Referal</option>
<option value="website">Website</option>
<option value="search">Search Engine</option>
<option value="card">Business Card</option>
</select>
<p>Enquiries:</p>
<textarea class="box_style" name="inquiries" cols="30" rows="10"></textarea>
<input class="box_style" type="submit" name="submit" value="Submit"/>
</form>
and this is the php
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$fName = $lName = $email = $cNum = $how = $enquiries = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fName = test_input($_POST["first_name"]);
$lName = test_input($_POST["last_name"]);
$cNum = test_input($_POST["contact_number"]);
$how = test_input($_POST["how"]);
$enquiries = test_input($_POST["enquiries"]);
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
print "<p>Please type a valid email address.</p>";
header("Location: www.mysite/thankyou.com");
}};
$email_from = 'my#email.com';
$email_subject = "New Inquiry";
$email_body = "You have received a new message from" ." ". "$fName" ." ". "$lName" ."\n".
"$inquiries"."\n".
"Referal Type:" ." ". "$how" ."\n".
"Contact Number:" ." ". "$cNum" ."\n";
$to = "my#email.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";
mail($to,$email_subject,$email_body,$headers);
?>
Thank You
Here's a simplified version of the OP's code that demonstrates how to display the error message by having the action attribute of the form be the same url as that which displays the form. The code also exemplifies some nice touches for the user:
<?php
include("php4myform.php");
?>
<html>
<head>
<title>Email Validate</title>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<label for="email">Email: </label>
<input id="email" name="email" required maxlength="50" value="<?php echo $e_mess; ?>">
<input type="submit" name="submit" value="Submit">
<input type="reset" id="clear" value="clear">
</form>
<script src="myJS4forms.js"></script>
</body>
</html>
php4myform.php:
<?php
$e_mess = "";
if ( isset($_POST['submit']) && $_POST != null) {
$tainted_email = trim($_POST["email"]);
$sanitized_email = filter_var($tainted_email, FILTER_SANITIZE_EMAIL);
if( !filter_var( $sanitized_email, FILTER_VALIDATE_EMAIL ) ) {
$e_mess = "Please type a valid email address.";
}
else
{
// Data is good to go.
}
}
myJS4forms.js:
var d = document;
d.g = d.getElementById;
var email = d.g("email");
var reset = d.g("clear");
function selFoc(obj){
obj.focus();
obj.select();
}
window.onload = function() {
selFoc( email );
};
reset.addEventListener("click",function(e) {
e.preventDefault();
email.value=null;
selFoc( email );
});
A few notes:
The drawback of testing with $_SERVER["REQUEST_METHOD"] is that the user might submit an empty form. Therefore, the PHP code in this example tests to see if the form was submitted and if the POST contains any data.
It is ill-advised to use htmlspecialchars() with filter_var and the parameter FILTER_EMAIL_SANITIZE; see this discussion and here, too. The code employs htmlspecialchars() instead to safeguard $_SERVER['PHP_SELF'] -- basis: this article.
I removed stripslashes() since magic quotes are deprecated and gone as of PHP5.4; see the online Manual. (Using addslashes() to escape data is inadvisable -- better to use mysqli_real_escape_string().) Also, filter_var with FILTER_SANITIZE_EMAIL will remove any slashes (see Manual).
If you redirect the user using a "header()" function, you need to stop the execution of the script. So the correct way would be something like this:
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
print "<p>Please type a valid email address.</p>";
header("Location: www.mysite/thankyou.com");
exit();
}
If you don't terminate the script, it will continue executing the rest of the file.
Secondly, if you print something to the user and immediately redirect him elsewhere, he will never see the message. If you want to do a redirection and show the message there, you need to store the message first, probably in a session variable, and then show it on the "landing page".
Ok, so I've got a contact form:
<?php
if (isset($_POST['subtest'])) {
$to = 'thomofawsome#gmail.com';
$name = $_POST['firstname'];
$lastName = $_POST['lastname'];
$email = $_POST['email'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$comments = $_POST['comments'];
$Message = <<< STOP
From: $name $lastName
Email: $email
In: $city, $state, $zip
Comments: $comments
STOP;
$subject = "Contact Request";
$headers = 'From: system';
if (mail($to, $subject, $Message, $headers)) {
echo '<div id="thanks">Mail sent</div>';
exit();
}
else {
echo 'Mail Failed';
}
}
?>
<form name="contact_form" action="" method="post">
<input type="hidden" name="subtest" value="true">
First Name:<br>
<input type="text" name="firstname">
<br>
Last Name:<br>
<input type="text" name="lastname">
<br>
Email Address:<br>
<input type="text" name="email">
<br>
City:<br>
<input type="text" name="city">
<br>
State:<br>
<input type="text" name="state">
<br>
Zip:<br>
<input type="text" name="zip">
<br>
Comments:<br>
<textarea name="comments"></textarea>
<br>
<input id="submit" type="submit" name="submit" value="Send">
<br>
</form>
The problem is I want the echo mail sent correctly formatted (with a green color, positioned correctly on the page, etc.). As you can see, I've put it in a div. When I submit the form though, I'm redirected back to the form page, except the entire form and footer disappear, and Mail sent appears on the bottom of the page (correctly formatted).
Any ideas?
The exit() function prevents the rest of the script from executing, which includes your form and footer. Remove it and it will work.
if (mail($to, $subject, $Message, $headers)) {
echo '<div id="thanks">Mail sent</div>';
} else {
echo 'Mail Failed';
}
As Raidenance pointed out, if someone refreshes this page after posting the form it will resend the email address. A better solution to this problem is to post your contact form to another url (/contact/submit for instance) and on completion of the script execution at that url simply redirect back to the contact form with a parameter
header("Location:/contact?success=true");
Then on your contact form page:
if (isset($_GET['success']) && $_GET['success'] == "true") {
echo '<div id="thanks">Mail sent</div>';
} else {
echo 'Mail Failed';
}
This will prevent the issue of the user reloading and receiving the email multiple times.
SOLVED - permissions
I want to walk through my debug process so that it might help anyone else working through the same thing... 1) I wiped both pages and replaced with the code that I knew worked. 2) I then changed the form piece by piece until I got it how i wanted and continued testing 3) I then copied the current php file completely and redirected my form to it. 4) it failed... I changed the permissions to 655 and wallah it worked. Now I can go about hacking about the PHP code to get what I want. thanks for all of the suggestions, you definitely led me down the road to my solution
SOLVED
I have two separate intake forms on a site. Intake form 1 works perfectly. I takes, name, email and comment and sends it through a sendmail script.
I also wanted an intake form for lead capture to track those that want to access the demo videos so I modified the code from the form (for the new page) and then created an additional php file called videoform.php - which is basically just a modified version of my sendmail.php file.
When I fill out the form it does nothing when I click on submit. It validates, as it not let you enter a null value in any of the fields but I am not sure what I am missing. Is it something simple (I am by no means PHP reliable) or can I simply not do that?
Here is the form and the php:
<div class="message"></div>
<form action="./php/videoform.php" method="POST" id="contact-form">
<p class="column one-half">
<input name="name" type="text" placeholder="Your Name" required>
</p>
<p class="column one-half">
<input name="email" type="email" placeholder="Your Email" required>
</p>
<p class="column one-half">
<input name="phone" type="text" placeholder="Your Phone" required>
</p>
<p>
<input name="submit" type="submit" value="Submit">
</p>
</form>
</div>
This is the PHP
<?php if(!$_POST) exit;
$to = "xxxxx#example.com";
$email = $_POST['email'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$content = $_POST['content'];
$subject = "You've been contacted by $name";
$content = "$name filled out a request to view the online videos:\r\n\n";
$content .= "Phone: $phone \n\nEmail: $email \n\n";
if ($success) {
header("Location: /videos.html");
exit;
} else {
header("Location: /video-form.html");
exit;
}
?>
I am comfortable with a number of coding formats but I am so weak when it comes to PHP. Any insight would be both appreciated and get me on the road to understanding PHP better.
Working scripts for comparison
Form
Send us a message
<p class="column one-half last">
<input name="email" type="email" placeholder="Your Email" required>
</p>
<p class="clear">
<textarea name="comment" placeholder="Your Message" cols="5" rows="3" required></textarea>
</p>
<p>
<input name="submit" type="submit" value="Comment">
</p>
</form>
</div>
PHP sendmail.php file
<?php if(!$_POST) exit;
$to = "xxxxx#example.com";
$email = $_POST['email'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$subject = "You've been contacted by $name";
$content = "$name sent you a message from your enquiry form:\r\n\n";
$content .= "Contact Reason: $comment \n\nEmail: $email \n\n";
if(#mail($to, $subject, $content, "Reply-To: $email \r\n")) {
echo "<h5 class='success'>Message Sent</h5>";
echo "<br/><p class='success'>Thank you <strong>$name</strong>, your message has been submitted and someone will contact you shortly.</p>";
}else{
echo "<h5 class='failure'>Sorry, Try again Later.</h5>";
}?>
From your php:
//...
$content = "$name filled out a request to view the online videos:\r\n\n";
$content .= "Phone: $phone \n\nEmail: $email \n\n";
if ($success) {
header("Location: /videos.html");
exit;
} else {
//...
You never define $success. Since it doesn't have a value, if ($success) fails, and it always enters the else portion of the statement. It looks like you're missing a line that's something like $success = mail($to, $subject, $content);