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
Related
I've been having an issue getting php to show a message when a form is submitted via email. I've googled it most of the day and tried a dozen or more fixes, but I cannot get it to show the message, it just jumps back to the previous page after execution, as per the header instructions in the php code. Any ideas (not ajax please).
Here's the html that calls the php.
<h2 class="u-text u-text-1">Questions or Comments?</h2>
<div class="u-clearfix u-custom-html u-expanded-width u-custom-html-1">
<form id="comment_form" action="form.php" method="post" style="none;width: 356px;padding: 10px;margin-top: 10px;float:top;margin-left: 40px;float: left;">
<input type="email" placeholder="Enter your email" id="email" name="email" size="40">
<br>
<br><!-- <input type="email" placeholder="Type your email" size="40"><br><br> -->
<textarea name="Name" placeholder="Name" rows="1" cols="40"></textarea>
<textarea name="comment" placeholder="Comments" rows="8" cols="80"></textarea>
<br>
<br>
<input type="submit" name="submit" value="Submit">
<br>
<br>
I know this has been asked millions of times, but nothing I've googled will work.
Here's the php.
<?php
$email;$Name;$comment;$captcha;
if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['Name'])){
$name=$_POST['Name'];
}if(isset($_POST['comment'])){
$comment=$_POST['comment'];
}if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "--nope-not showing it--";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
if($responseKeys["success"]) {
$status = "Submission Successful";
// echo '<h2>Thanks for posting comment</h2>';
$subject = "New Form Submission";
$to = "admin#apt905.com";
$comments = "name: $name \r\n email: $email \r\n $comment";
$headers = "From: $email \r\n";
mail($to,$subject,$comments,$headers);
} else {
$status = "Submission Error";
// echo '<h2>You are a spammer ! Get the #$%K out</h2>';
}
if(isset($_REQUEST["destination"])){
header("Location: {$_REQUEST["destination"]}");
}else if(isset($_SERVER["HTTP_REFERER"])){
header("Location: {$_SERVER["HTTP_REFERER"]}");
}else{
/* some fallback, maybe redirect to index.php */
}
?>
I will just assume, that problem is not because all echo is commented out and all conditions are working as expected.
Since you can not use header() when there is output, you need to first set headers, and only then show text:
header("refresh:5; url={$_REQUEST["destination"]}");
/* ... */
echo '<h2>Thanks for posting comment</h2>';
This will start redirection after 5 seconds and only then show message (first process information and set message & url to use, then at the end set header and output message)
Finally figured it out, thanks Justinas. I made a change in your header suggested statement to this and it works fine.
header("refresh:5; url={$_SERVER['HTTP_REFERER']}");
Being so bad at PHP, I've decided to post here as a last resort.
I want to add a "who" variable to the message body of emails sent via PHP contact form. The form works fine for name, email and message but the "who" input I would like to be a part of the email message that comes through, as a way to communicate who is being referred.
I have tried to add $who=$_REQUEST['who']; as well as $who to the mail line but neither work, the latter doesn't even send an email at all.
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
<input name="name" type="text" placeholder="Your Name" value="" size="14"/>
<input name="email" type="text" placeholder="Your Email" value="" size="14"/>
<textarea name="who" placeholder="Who should we contact?" rows="1" cols="14"></textarea>
<textarea name="message" placeholder="Description" rows="2" cols="14"></textarea><br>
<input type="submit" class="button special" value="SUBMIT"/>
</form>
<?php
}
else
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "All fields are required, please fill out the form again.";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Referral for ******* **";
mail("chris#********.com.au", $subject, $message, $from);
}
{
echo "<script type='text/javascript'>window.location.href ='../thanks.php';</script>";
}
}
?>
In PHP . is the concatenation operator which returns the concatenation of its right and left arguments
Try this
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'] . "\n\rFrom: " . $_REQUEST['who'];
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';
}
?>
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);
I don't think my title does this question justice but it may get confusing and I don't want to extend the title over several lines.
Here goes:
I have a single page website which has a contact form with the below code:
<form class="move-down" name="contactform" method="post" action="contact-form-handler.php">
<div class="controls controls-row">
<input id="name" name="name" type="text" class="span3" placeholder="Name">
<input id="email" name="email" type="email" class="span3" placeholder="Email address">
</div>
<div class="controls">
<textarea id="message" name="message" class="span6" placeholder="Your Message" rows="7"></textarea>
</div>
<div class="controls pull-right">
<button id="contact-submit" type="submit" class="btn btn-default">Send it!</button>
</div>
</form>
As you can see its action is to call an external php file called "contact-form-handler", which is shown below:
<?php
$errors = '';
$myemail = 'hello#wunderful.co.uk';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= die(header('Location: #errorModal'));
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= die(header('Location: #errorModal'));
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' modal
header('Location: #thanksModal');
}
?>
<?php
?>
This has been working fine but as my new site is one page I don't want separate pages loading, nor do I just want to echo black text on a white background.
So my question is - How do I show the Bootstrap Modal window when the submit button is clicked, with php code from inside the external file AND without the page reloading?
I hope it can be done. If it can't can someone help me launch a modal that says error or thanks when the submit button is clicked?
yes you can. Since you are not using oop way you can do this
1) on page submit you will assign some $mail_send = true; after email is send
2) you fill then say <?php if ($mail_send) { ?> code for modal here <?php } ?>
3) Drop this header('Location: #thanksModal'); you do not need that.
Put $mail_send = true; instead of that.
that is all.