Issue with simple PHP Contactform - php

So I have some issues with my PHP Contactform on a HTML site.
Code below is what I have written in HTML. (that's not te problem)
<form action="sendmail.php" method="POST" class="contact-form">
<input type="text" placeholder="Amount" name="amount">
<input type="text" placeholder="Name" required name="name">
<input type="text" placeholder="Email Address" required name="email">
<div class="validation">
<button class="btn" name="submit">Send request</button>
// END HTML code. (BELOW is starts PHP).
$email_to = "domain#website.com";
$amount = $_POST["amount"];
$name = $_POST["name"];
$email = $_POST["email"];
$email_subject = "DOMAINNAME";
$headers = "From: " . $email . "\n";
$headers .= "Reply-To: " . $email . "\n";
$message = 'Name: ' . $name . ', email: ' . $email . ', amount: ' . $amount;
ini_set("sendmail", $email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false)
{$sent = mail($email_to, $email_subject, $message, $headers, "-f" .$email);}
{
header("Location:https://website.com");
} else {
echo "There has been an error sending your comments. Please try later.";
}
What do I wrong? I only wanna receive the --> name, amount and mail.
Only when I press submit on my HTML site, it's send me to website.com/sendmail.php (HTTP ERROR 500).
Thank you guys.

Related

PHP - Email form is sending over 50 mails after form submit

I have a problem that after I fill out the contact form on my HTML website I receive over 50 same E-mails. Its a HTML form connected to contact.php file which code is shown bellow. I have set everything but maybe there is a problem in my code or somewhere else.
My code is over here
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+ (ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
$verify = $_POST['verify'];
if(trim($name) == '') {
echo '<div class="error_message">Vyplnte meno.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Vyplnte email.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Zadali ste nesprávny e-mail, skúste to znovu.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Vyplnte text správy.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
$address = "noreply#marcelaskolenia.sk";
$address = "lubosmasura#gmail.com";
$toCustomer = $email;
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'Mate novu spravu od ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "Mate novu spravu od $name." . PHP_EOL . PHP_EOL;
$e_content = "\"$subject\"" . "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "Kontaktujte $name cez email, $email alebo cez mobil $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers .= 'To: Test <noreply#marcelaskolenia.sk>' . "\r\n";
$headers .= 'From: Testk <noreply#marcelaskolenia.sk>' . "\r\n";
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h3 class'mark'>Sprava bola odoslana.</h3>";
echo "<p>Dakujeme <strong>$name</strong>, Vasa sprava nam bude dorucena.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
HTML code
<div class="contact_form">
<div id="message"></div>
<form id="contactform" class="row" action="contact.php" name="contactform" method="post">
<div class="col-md-12">
<input type="text" name="name" id="name" class="form-control" placeholder="Meno">
<input type="text" name="email" id="email" class="form-control" placeholder="Email">
<input type="text" name="phone" id="phone" class="form-control" placeholder="Telefónne číslo">
<input type="text" name="subject" id="subject" class="form-control" placeholder="Predmet">
<textarea class="form-control" name="comments" id="comments" rows="6" placeholder="Text správy"></textarea>
<button type="submit" value="SEND" id="submit" class="btn btn-primary"> ODOSLAŤ</button>
</div>
</form>
</div>
</div><!-- end col -->
Any Ideas why is this happening?
Thank you.

Form waits for second submission to push through first submission

I'm new to development and I'm trying to build a contact form using php that pulls the info from a contact form. My contact form works and collects the data as needed, but when I click submit the first time I don't receive the information to my inbox. When I refresh the page, complete the form a second time and click submit once more, I receive both submissions to my inbox at the same time. It's as if the first submission waits to be pushed through by the second submission. Can anyone explain why this is happening and how to stop it?
I've seen a lot of posts regarding submissions happening twice but my issue is the first doesn't come through until the second is sent.
Here is my PHP
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$mailFrom = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$body = $_POST['body'];
$radio = $_POST['time'];
$mailTo = "myemail#gmail.com";
$headers = "From: " . $mailFrom;
$txt = "You have received an enquiry from: " . $name .
"\n\n Phone Number: " . $phone .
"\n\n Address: " . $address .
"\n\n Message: " . $body .
"\n\n Time to call: " . $radio;
mail($mailTo, $subject, $txt, $headers);
header("Location: index-contact.php?submission");
}
I'm testing on localhost8888 using MAMP Pro.
Here is HTML:
<form class="contact-form" action="contactform.php" method="post" id="form">
<label for="name">Full Name:</label><br>
<input type="text" id="name" name="name" placeholder="Please enter your name" required>
<label for="email">Email Address:</label><br>
<input type="email" id="email" name="email" placeholder="Please enter your email address" required>
<label for="phone">Phone Number:</label><br>
<input type="text" id="phone" name="phone" placeholder="Please enter your phone number" required></input>
<label for="subject">Subject</label><br>
<input type="text" id="subject" name="subject" placeholder="Please enter a subject" required></input>
<label for="address">Postcode:</label><br>
<input type="text" name="address" placeholder="Please enter your postcode"></input><br>
<label for="body">Comments:</label><br>
<textarea name="body" placeholder="Please enter your message"></textarea>
<input type="radio" id="morning" name="time" value="morning">Morning</input>
<input type="radio" id="afternoon" name="time" value="afternoon">Afternoon</input>
<input type="radio" id="anytime" name="time" value="anytime">Anytime</input>
<button type="submit" id="submit" name="submit">Send Message</button>
</form>
This happens because when you update the page, you will be resending the POST.
As this is a contact form, i suggest installing Google reCaptcha. Thus, it will be necessary to resolve the captcha and this will not happen.
There are other ways. One of them would be to store user data in a database and only authorize a sending by IP or session at a certain time.
Or you can just work with direct session and prevent this from happening, using the function in your code:
function prevent_multi_submit($type = "post", $excl = "contact") {
$string = "";
foreach ($_POST as $key => $val) {
// this test is to exclude a single variable, f.e. a captcha value
if ($key != $excl) {
$string .= $val;
}
}
if (isset($_SESSION['last'])) {
if ($_SESSION['last'] === md5($string)) {
return false;
} else {
$_SESSION['last'] = md5($string);
return true;
}
} else {
$_SESSION['last'] = md5($string);
return true;
}
}
Your code will look like this:
session_start();
if (isset($_POST['submit']) and prevent_multi_submit()) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$mailFrom = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$body = $_POST['body'];
$radio = $_POST['time'];
$mailTo = "myemail#gmail.com";
$headers = "From: " . $mailFrom;
$txt = "You have received an enquiry from: " . $name .
"\n\n Phone Number: " . $phone .
"\n\n Address: " . $address .
"\n\n Message: " . $body .
"\n\n Time to call: " . $radio;
mail($mailTo, $subject, $txt, $headers);
header("Location: index-contact.php?submission");
}
EDIT 1:
Or, add a simple parameter to the URL that redirects, so that a second POST is not authorized:
if (isset($_POST['submit']) and $_GET["sent"] != "ok") {
$name = $_POST['name'];
$subject = $_POST['subject'];
$mailFrom = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$body = $_POST['body'];
$radio = $_POST['time'];
$mailTo = "myemail#gmail.com";
$headers = "From: " . $mailFrom;
$txt = "You have received an enquiry from: " . $name .
"\n\n Phone Number: " . $phone .
"\n\n Address: " . $address .
"\n\n Message: " . $body .
"\n\n Time to call: " . $radio;
mail($mailTo, $subject, $txt, $headers);
header("Location: index-contact.php?sent=ok");
}
Read more about HTTP GET variables at PHP.net

PHP email and url validation

So I've made myself a little contact form with php, css, and html. But when I try to add a email validation it still sends the email and doesn't change the style of the input to red (Like I would like it to). Another issue I'm having is the button redirecting to the top of the page (which I do not want it to do). Last I can I make the input keep the text rather than remove it once submitted
HTML:
<div id="contact">
<div class="container">
<form id="contact-form" method="post">
<h1>Contact Form</h1>
<fieldset>
<input placeholder="Your Name" type="text" name="name" required>
</fieldset>
<fieldset>
<input placeholder="Your Email Address" type="email" name="email" id="email-input" required>
</fieldset>
<fieldset>
<input placeholder="Your Phone Number (optional)" type="tel" name="phone" required>
</fieldset>
<fieldset>
<input placeholder="Your Web Site (optional)" type="url" name="site" required>
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." name="message" required></textarea>
</fieldset>
<fieldset>
<button type="submit" id="contact-submit" name="submit">Submit</button>
</fieldset>
</form>
</div>
</div>
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$visitors_site = $_POST['site'];
$message = $_POST['message'];
$email_from = 'mattmowen1#gmail.com';
$email_subject = 'New Contact Submission';
$to = 'mattmowen1#gmail.com';
$headers = "From:" . $email;
$headers = "Contact Submission From: " . $email;
$message1 = "Name: " . $name;
$message2 = "\n\nEmail: " . $email;
$message3 = "\n\nPhone: " . $phone;
$message4 = "\n\nTheir Site: " . $visitors_site;
$message5 = "\n\nMessage: " . $message;
$email_body = $message1 . $message2 . $message3 . $message4 . $message5;
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
mail($to, $email_subject, $email_body,$headers);
} else {
echo "<style>#email-input {color:red}</style";
}
?>
Try this for email validation in php
<?php
if (isset($_POST) && !empty($_POST)) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$visitors_site = $_POST['site'];
$message = $_POST['message'];
$email_from = 'mattmowen1#gmail.com';
$email_subject = 'New Contact Submission';
$to = 'mattmowen1#gmail.com';
$headers = "From:" . $email;
$headers = "Contact Submission From: " . $email;
$message1 = "Name: " . $name;
$message2 = "\n\nEmail: " . $email;
$message3 = "\n\nPhone: " . $phone;
$message4 = "\n\nTheir Site: " . $visitors_site;
$message5 = "\n\nMessage: " . $message;
$email_body = $message1 . $message2 . $message3 . $message4 . $message5;
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
mail($to, $email_subject, $email_body,$headers);
} else {
echo "<style>#email-input {color:red}</style>";
}
}
?>
As per our chat conversation. I am adding jquery ajax function according to your form requirement.
You need to create new file email.php and put your php code into this separate php file
<script>
var url = 'email.php';
$.ajax({
url : url,
type : "POST",
dataType : "JSON",
data : $('#contact-form').serialize(),
success : function(response) {
if (response.error == 0) { // success
$('#contact-form')[0].reset();
alert('Form submitted successfully. We will contact you asap.');
} else { // error
$('#email-input').css('color', 'red');//in case of email error
alert('ERROR MESSAGE');//form is invalid
}
}
})
</script>
To handle JSON request you need to send JSON object in response. So change you php code snippet like this:
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
mail($to, $email_subject, $email_body,$headers);
exit(json_encode(array('error' => 0)));
} else {
exit(json_encode(array('error' => 1)));
}

How can i add a default message with php mail function?

I have created an html form that after the user clicks "send" redirects to mail.php which contains php mail function that works and sends the desired message.
Is there any way to also add a default message for example "This was sent from the website" to the email?
Form from index.html
<form method="post" action="mail.php">
<div class="form-style">
<h1 class="formh1">Full Name</h1>
<input type="text" id="name" name="name" placeholder="Full name" required>
<h1 class="formh1">Email address</h1>
<input type="email" id="email" name="email" placeholder="Email address" required>
<h1 class="formh1">Message</h1>
<textarea rows="4" cols="50" id="message" name="message" placeholder="Give us your thought" required></textarea>
<div class="button-form">
<input type="submit" name="send" value="Send" />
</div>
</div>
</form>
Mail.php
<?php
if (isset($_POST['send'])) {
$from = 'myemail'; // Use your own email address
$subject = 'The following message was sent from the website';
$message = 'Fullname: ' . $_POST['name'] . "\r\n\r\n";
$message .= 'Email address: ' . $_POST['email'] . "\r\n\r\n";
$message .= 'Message: ' . $_POST['message'];
$name = trim(filter_input(INPUT_POST,"name",FILTER_SANITIZE_STRING));
$email = trim(filter_input(INPUT_POST,"email",FILTER_SANITIZE_EMAIL));
$details = trim(filter_input(INPUT_POST,"message",FILTER_SANITIZE_SPECIAL_CHARS));
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
header('Location: index.html');
if ($email) {
$headers .= "\r\nReply-To: $email";
}
$headers = "From: ".$_POST['email']."\r\n";
$headers .= 'Content-Type: text/plain; charset=utf-8';
$success = mail($from, $subject, $message, $headers);
}
?>
Just add the default email your would like to send to the $message variable:
$message = 'This is my default message lalalalalal'
You just amend before, or after... wherever you want to inject that content.
When you use $var .= "something added!"; - You're appending/concatenating additional text in this case.
When you use $var = "something added!"; - w/o The .= you've reset the variable to the new string.
Think of .= being the same as $message = $message . "String being added to message"
$from = 'myemail'; // Use your own email address
$subject = 'The following message was sent from the website';
#EXAMPLE HERE - Also note I added htmlspecialchars
#These will convert any misc. characters to html readable content.
#Test with it, see if it fits. Just don't add it to $email = trim...
$message = "Your friend " . htmlspecialchars($_POST['name']) . " has sent you a message from www.mywebsite.com"\r\n\r\n;
$message .= 'Fullname: ' . htmlspecialchars($_POST['name']) . "\r\n\r\n";
$message .= 'Email address: ' . htmlspecialchars($_POST['email']) . "\r\n\r\n";
$message .= 'Message: ' . $_POST['message'];
$name = trim(filter_input(INPUT_POST,"name",FILTER_SANITIZE_STRING));
$email = trim(filter_input(INPUT_POST,"email",FILTER_SANITIZE_EMAIL));
$details = trim(filter_input(INPUT_POST,"message",FILTER_SANITIZE_SPECIAL_CHARS));
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

PHP mail form is not working

I m having a problem with my email php form, when I click in the submit button an other page shows up saying There was a problem with your e-mail ()
I don't no what I am doing wrong?
here is my code:
html code
<!-- Subscription Form -->
<form class="email" action="form.php" method="post">
<input class="get_notified" type="text" placeholder="Enter your email address ..."/>
<button type="submit" class="go" /></form>
<!-- End Subscription Form -->
</div>
</div>
</body>
php code
<?php
$to = "email#mydomain.com";
$from = "email#mydomain.com";
$headers = "From: " . $from . "\r\n";
$subject = "New subscription";
$body = "New user subscription: " . $_POST['email'];
if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) )
{
if (mail($to, $subject, $body, $headers, "-f " . $from))
{
echo 'Your e-mail (' . $_POST['email'] . ') has been added to our mailing list!';
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
You'll need to add a name="email" field to your HTML form in order for PHP to be able to fetch it using $_POST['email']
<input class="get_notified" name="email" type="text" placeholder="Enter your email address ..."/>

Categories