PHP script keeps sending Email evertime the page is loaded - php

I have put together a simple contact form for my website. Using PHP to POST the data and send directly to my email address. But for some reason every time I visit the page on my website. I still get the test message Displaying under the Form. Then when I reload the website and visit the link again it still displays the thank you message. and automatically sends an email. Im still in testing mode 2 days before my launch and I need this figure out. Considering I am novice to php I dont know what goes where.... check out my website to get a live view https://trillumonopoly.com (click "Contact Us" link in menu) I would like for the contact form to disappear and echo the thank you message once sent. And reset after the page is reloaded. I am also using Jquery ajax to load all my pages into a div container. So I would like to keep the content inside that div without forwarding to the Echo message page, leaving my index page
Heres My ajax code
$(document).ready(function () {
loadMainContent('main');
$('body').delegate('.navMenu', 'click', function (event) {
event.preventDefault();
loadMainContent($(this).attr('href'));
});
});
function loadMainContent(page) {
$('#main').load('pages/' + page + '.php');
}
here is html for the form:
<div class="general row container-fluid"><br>
<center><img src="img/divider.png" class="img-fluid"></center>
<div class="col-lg-6 col-sm-12">
<img src="img/logo.png" class="img-fluid" height="540px" width="540px">
</div>
<div class="col-lg-6 col-sm-12 container"><center>
<br><h1 class="form-title">Contact Us</h1><br></center>
<div class="container">
<form action="pages/mail.php" method="GET" class="box2">
NAME:
<input type="text" name="name" placeholder="YOUR NAME HERE" required>
<br><br>
EMAIL:
<input type="email" name="email" placeholder="YOUR EMAIL HERE" required>
<br><br>
MESSAGE:<br>
<textarea name="message" rows=10 cols=23 placeholder="YOUR MESSAGE HERE" required></textarea>
<br><Br>
<button type="submit" value="Message Sent" class="btn btn-danger btn-lg" style="background-color:"red">SUBMIT</button
</form>
<center><?php include('mail.php'); ?></center>
</div>
</div>
</div>
Here is My simple PHP:
<?php
$name = $POST['name'];
$email = $POST['email'];
$message = $POST['message'];
mail("info#trillumonopoly.com","ILLUMONOPOLY WEB Contact", $message,"From: $email\r\n");
echo "Thank You For Contacting Us!";
?>

Better than check everything before send mail.
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])){
$name = $POST['name'];
$email = $POST['email'];
$message = $POST['message'];
mail("info#trillumonopoly.com","ILLUMONOPOLY WEB Contact", $message,"From: $email\r\n");
echo "Thank You For Contacting Us!";
}
And send POST request to the index, not mail.php.
<form action="" method="POST">
...
So the user can see your message at the end of contact form.

Related

PHP contract form, Message Sent

I made a PHP contact form which sends an email to me.
And I would like to inform the user that the message had been sent after refreshing the page.
I was able to make a pop up only before refreshed the page, with this the problem was that if the user leaves the page before clicking ok, the message won't be sent.
This is my current code:
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$subject=$_POST['subject'];
$mailFrom=$_POST['mail'];
$message=$_POST['message'];
$mailTo = "something#something.org";
$headers = "From: ".$mailFrom;
$txt ="You have received an e-mail from".$name.".\n\n" .$message;
if ($name != '' && $mailFrom != '') {
if (mail ($mailTo, $subject, $message, $mailFrom)) {
echo '<p>Your message has been sent.</p>';
} else {
echo '<p>Something went wrong, go back and try again.</p>';
}
} else {
echo '<p>You need to fill in all required fields.</p>';
}
}
mail($mailTo,$subject,$txt,$headers);
header("Location: index.php") ;
?>
HTML:
<div class="modal-bg">
<div class="modal">
<form class="contact-form" action="contactform.php" method="post">
<h2>Contact Us!</h2>
<label for="name">Name: </label> </br>
<input type="text" name="name" placeholder="Your name"> </br>
<label for="email">E-mail</label> </br>
<input type="text" name="mail" placeholder="Your e-mail"> </br>
<label for="subject">Subject: </label> </br>
<input type="text" name="subject" placeholder="Subject"> </br>
<label for="message">Message: </label> </br>
<textarea name="message" class="message" placeholder="Message" rows="15" cols="50"></textarea> </br>
<button type="submit" name="submit"> SEND </button>
</form>
<span class="modal-close">X</span>
</div>
</div>
I used a different method. Made a PHP page which says it is successful and redirects it after 5 seconds
<html>
<head>
<meta http-equiv="refresh" content="5;URL=http://address.com">
</head>
<body>
<div id="messagesent">
<p>Message has been sent successfully<p>
<p> This page will be redirect after 5 seconds. Please wait ...<p>
</div>
</body>
</html>
Ok, so what you have there is something i have had trouble with in the past: you are redirecting with a PHP header method, which is part of a (mostly) server side language which ends all of its functions as soon as the page is loaded: what i mean by this is that the code you have there will redirect the user out of your page before alerts or messages can be given out.
What i suggest you do is a little something like this in PHP:
$alert = "this is an alert and gets set whenever something happens";
//instead of an alert you could also create the paragraph with a button which triggers the redirect.
echo
"
<script>
window.onload = function(){alert('$alert');}
//this will fire the alert and stop any other thing from happening before the alert is closed
window.location.href = "https://target_page.com";
//this redirects the user to the wanted page, NB: do use href as other methods may directly redirect without waiting for the alert to display
</script>
";
Let me know if this is what you were looking for :)

Sending emails with Mailgun occasionally hangs and doesn't send email

So ive just implmented mailgun into a website for sending contact form info.
This works some of the time, but mostly the page hangs when i press send with the message "waiting for url..." in the bottom left of chrome.
There is no ssl on the server hence the strange mailgun constructor.
This is my php which is placed just inside the body of my website.
<?php
require 'mailgun-php/vendor/autoload.php';
use Mailgun\Mailgun;
if(isset($_POST['register'])){
$message = "Contact Form.\n\n".
"Name: ".$_POST['name']."\n".
"Email: ".$_POST['email']."\n".
"Message: ".$_POST['message']."\n";
$mg = new Mailgun(*my key*, "api.mailgun.net", "v2", false);
$domain = *my domain*;
$mg->sendMessage($domain, array(
'from'=>'Contact Form <build#<url>>',
'to'=> *email*,
'subject' => ' Contact Form',
'text' => $message
)
);
header('Location: ?sent=1');
}
?>
This is the form code:
<form method="post" action="index.php">
<div class="row 50%">
<div class="6u 12u$(mobile)"><input type="text" class="text" name="name" placeholder="Name" /></div>
<div class="6u$ 12u$(mobile)"><input type="text" class="text" name="email" placeholder="Email" /></div>
<div class="12u$">
<textarea name="message" placeholder="Message"></textarea>
</div>
<div class="12u$">
<button class="button" type="submit" name="register"> Send Message </button>
</div>
</div>
</form>
I'm not getting any errors when the email is not sent. The page will eventually reload after the submit button is pressed but the header redirect is not being applied (which im assuming is because the email was not sent successfully).
The php error logs do not show anything going wrong either.
Thanks
Maybe that's a (very) late answer, but I've just met the same problem. And I discovered, that Mailgun has whitelist of IP addresses, so in case you haven't added there your public IP address, the connection to Mailgun's API will never be established.
At the moment of writing this answer, the whitelist is present under this link: https://app.mailgun.com/app/account/security/api_keys

Sending an email using php

Given a standard html form such as the one below;
<form method="post" action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>>
<div class="row half">
<div class="6u"><input type="text" placeholder="Name" name="name" /></div>
<div class="6u"><input type="text" placeholder="Email" name="email" /></div>
</div>
<div class="row half">
<div class="12u"><textarea name="message" placeholder="Message" name="message"></textarea></div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" class="button" value="Send Message" name="submit" /></li>
<li><input type="reset" class="button alt" value="Clear Form" name="clear"/></li>
</ul>
</div>
</div>
</form>
And the following php
if(isset($_POST['submit'])){
$to = "enquiries#appcloudkent.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Website Enquiry";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
if(isValidString($from) && isValidString($name) && isValidString($message)){
mail($to,$subject,$message,$headers);
}
}
It is possible to send an email, however, this approach causes a couple of problems. Because my form is at the bottom of the page, when send is clicked the page is redirected back and the focus goes back to the top of the page.
What is the correct way to provide adequate user feedback to let the user know the email was sent, is it possible to navigate back to the page and automatically scroll to the bottom - allowing me to change the send button to green or something?
Failing that, is there a better approach to doing this?
Thanks
Add an anchor link before your form.
<a id="anchorName"></a>
Post your form to the anchor.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>#anchorName">
The form action should point to the page itself (like it does in your example) so you can display error messages from validation (like you don't).
If the form is not at the top of your page you can add an anchor:
<h2><a name="theForm">The form</a></h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>#theForm">
If the form is processed properly (=mail sent), it is good practice to redirect to another page, showing a success message. So pressing F5 doesn't submit the form again (and send another mail).
if (mail($to,$subject,$message,$headers)) {
// redirect to page showing success message and exit script
} else {
// redirect to page showing error message and exit script
}
I usually redirect to the same page again, but attach an param ($_SERVER["PHP_SELF"].'?mail_success=1') and then inside the template I decide whether to show the success message, error message or the form:
if (isset($_REQUEST['mail_success'])) {
// show success message
} elseif (isset($_REQUEST['mail_error'])) {
// show error message, technical issues, try again bla bla
} else {
// show the form (including validation errors if necessary)
}
You could submit the form using an XMLHttpRequest, and cancel the default action of pressing submit. jQuery's .post() and event.preventDefault() methods are particularly good at that.

How do I make contact form success message appear in same page

My website is one pager with nav that links to different parts of the page within the same document. So my contact is at stie.com/#contact rather than site.com/contact.html
I have my contact form coded in html using post method linking to mail.php. Upon hitting the submit button I get redirected to site.com/mail.php where the "Your message was succesfully sent" is displayed. How do I get it so that it displays right on top of the contact form since I don't have a contact.html file to turn into a contact.php and put the php code right where I want the success message to display?
<div class="row">
<div class="12u">
<form method="post" action="mail.php">
<div>
<div class="row half">
<div class="6u">
<input type="text" name="name" id="name" placeholder="Name" />
</div>
<div class="6u">
<input type="email" name="email" id="email" placeholder="Email" />
</div>
</div>
<div class="row half">
<div class="12u">
<input type="text" name="subject" id="subject" placeholder="Subject" />
</div>
</div>
<div class="row half">
<div class="12u">
<textarea name="message" id="message" placeholder="Message"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
Send Message
Clear Form
</div>
</div>
</div>
</form>
</div>
My Mail.php
<?php
//GET INFO FROM CONTACT FORM
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST ['subject'];
$message = $_POST['message'];
$from .= $_POST ['email'];
$to = 'email#site.com';
// compose headers
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
//POST SUBMIT
if ($_POST['sumbit']);
if ($name != '' && $subject != '' && $message !='' && $email != '') {
if (mail ($to, $subject, $from, $message, $headers)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
} else {
echo '<p>Please fill in all required fields!!</p>';
}
?>
You can use URL parameters with PHP:
<?php
$confDisplay = 'display:none;';
// if the url param exists, display confirmation
if(isset($_GET["confirm"]) && $_GET["confirm"]==true){
$confDisplay = 'display:inline;';
}
?>
...
<div style="<?php echo $confDisplay; ?>">
Your form has been submitted!
</div>
...
Just set your form action URL to the same page with ?confirm=true at the end.
Make your action field empty. Put action="" instead of action="mail.php" Then include your mail.php content inside your contact page. As you know, you have to save that page as PHP, too; for example, mycontactform.php. In this way you have more control over the content and format of the "your message submitted" message. If you separate mail.php you can't address divisions in the mycontactform.php.
Security and vulnerability of PHP codes you are using should be addressed after you have completed the page coding and tested it as up and running in your desired format, since it needs more in-depth study of PHP conventions and usages. source: A Set of Step by Step Tutorials Using HTML5, CSS3 and PHP (8)
Note that your script mail.php is vulnerable to headers injection attack. You need to escape your variable $_POST['email']. You have to remove the special characters \n and \r. This can be made easily by using the str_replace function.

how do I get the message after submit to appear inside the pop up instead of on a different page

I have a contact form that I'm using Jquery .load to import a php file into any of the pages the nav will be on. Example below.
http://madaxedesign.co.uk/dev/index.html
I'm aware that the action form needs to be changed so it is connected to the right place. But how would I do that if it is on different pages and imported into a page. Because at the moment it is set to contact.php but after it is submitted it goes to that page and doesn't import the message into the pop up. So really I need it to be the file name depending on what page it is on.
So I suppose the question is how do I get the message after submit to appear inside the pop up instead of on a different page?
Code:
<?php
$your_email = "maxlynn#madaxedesign.co.uk";
$subject = "Email From Madaxe";
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";
$thankyou_message = "<p>Thank you. Your message has been sent. We Will reply as soon as possible.</p>";
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
if (!isset($_POST['txtName'])) {
?>
<form method="post" action="contact.php">
<div id="NameEmail">
<div>
<label for="txtName">Name*</label>
<input type="text" title="Enter your name" name="txtName" />
</div>
<div>
<label for="txtEmail">Email*</label>
<input type="text" title="Enter your email address" name="txtEmail" />
</div>
</div>
<div id="MessageSubmit">
<div>
<textarea maxlength="1200" title="Enter your message" name="txtMessage"></textarea>
<label for="txtMessage">Message</label>
</div>
<div>
<input type="submit" value="Submit" /></label>
</div>
</div>
</form>
<?php
}
elseif (empty($name) || empty($email) || empty($message)) {
echo $empty_fields_message;
}
else {
$referer = $_SERVER['HTTP_REFERER'];
$this_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];
if ($referer != $this_url) {
echo "You do not have permission to use this script from another URL, nice hacking attempt ;p.";
exit;
}
mail($your_email, $subject, $message, "From: $name <$email>");
echo $thankyou_message;
}
?>
You should use ajax, send the email without refreshing page.
What you want to do is only possible in javascript, this is a language that gets executed by the browser. Javascript self is a nasty language but there are many extensions/plugins to make this very easy like jQuery. i suggest you to learn this language, you will find a new world opening in web development ;-). eg: http://learn.jquery.com/
give your form an id:
<form method="post" id="test-form" action="contact.php">
so you can reference to it with jquery
now you can catch the form submit action with jQuery:
$('#test-form').submit(function() {
//send your data to your server and get the html data
$.post('contact.php', $(this).serialize(), function (data){
//here you can add the (html)data returned by the action to your page.
$('body').append(data); //append data to body of html page
})
return false; //stop form from going to the next page
});
this code is based on a javascript plugin: jQuery, if you want to do anything dynamic on your page without reloading the page, you need to use javascript.

Categories