PHP email and url validation - php

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)));
}

Related

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

Google reCaptcha v2 (Checkbox) Verification

I have a contact form which is working fine. I have Integrate Google ReCaptcha v2 with it and it is showing below my contact form but form will be submitted either user checked reCaptcha or not. I want to verify it that form only goes submit if user has checked google ReCaptcha otherwise it shows a message to the user to check it.
Here is my HTML Form (contact.html):
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer>
</script>
</head>
<body>
<form action="contact_us.php" method="post">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Your
Name *" required>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email *" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="form-control" placeholder="Contact Number">
</div>
<div class="form-group">
<textarea class="form-control textarea" name="message" placeholder="Message"></textarea>
</div>
<div class="form-group">
<div class="g-recaptcha" data sitekey="have_enter_my_site_key_here"></div>
</div>
<div class="form-group">
<input type="submit" name="submit" class="form-control btn-
submit" Value="Send">
</div>
</form>
</body>
</html>
Here is PHP code as (contact_us.php):
<?php
ob_start();
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$email_from ='';
$email_subject = "Contact Form";
$email_body = "User Name: $name \n".
"User Email: $email \n".
"Phone Number: $phone \n".
"User Message: \n $message \n";
$to = "my_Email_here";
$headers = "From: $email_from \r\n";
$headers = "Reply-To: $email \r\n";
$result = mail($to,$email_subject,$email_body,$headers);
if($result) {
echo "Sent Successfully";
}
else{
echo "Something Went wrong. Please try again";
}
?>
Help me how should I verify google ReCaptcha with my HTML form.
<?php
if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
// Your site secret key obtained from Google
$secret = '#####################################';
$grResponse = $_POST['g-recaptcha-response'];
// Verify with Google Servers
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $grResponse);
$responseData = json_decode($verifyResponse);
if ($responseData->success) {
ob_start();
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$email_from = '';
$email_subject = "Contact Form";
$email_body = "User Name: $name \n" . "User Email: $email \n" . "Phone Number: $phone \n" . "User Message: \n $message \n";
$to = "my_Email_here";
$headers = "From: $email_from \r\n";
$headers = "Reply-To: $email \r\n";
$result = mail($to, $email_subject, $email_body, $headers);
if ($result) {
echo "Sent Successfully";
}
else {
echo "Something Went wrong. Please try again";
}
} else {
echo "################################";
}
} else {
echo "################################";
}
?>
Please check below code:

php Email form / if / else if / error messages

I have tried to create php email form. The form was basically working, but I wanted to add validation functions like I did on 'name'
However, It doesn't work when I empty 'name' and just sent an email.
Any help would be really appreciated.
htmlfile
<form action="php_mini.php" method="post">
Name:
<input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Email:
<input type="text" name="email">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Phone:
<input type="text" name ="phone">
<br><br>
Comment:
<!--<textarea name="comment"></textarea>-->
<!--<input type = "text" name = "comment">-->
<textarea name="comment" rows="5" cols="40"></textarea>
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="submit" value="Submit">
</form>
php
echo '<pre>';
print_r( $_POST );
echo '</pre>';
$headers = 'MIME-Version: 1.0' . "\r\n" .
'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
'From: Design_customers <customers.com' . " \r\n" .
//'Reply-To: vader#deathstar.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
//error msg
$nameErr = $emailErr = $phoneErr = "";
$name = $email = $comment = $phone = "";
//receiver
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
$email = $_POST['email'];
/*$message = $_POST['comment'];*/
$message = 'You got a message from a customer.:
Name: '.$_POST['name'].'
Email: '.$_POST['email'].'
Phone: '.$_POST['phone'].'
Comment: '.$_POST['comment'];
//sender
$from = 'From: Customer';
$subject = 'Customer Inquiry';
mail( $email, $subject, $message, $from );
use if(isset($_POST["name"])) to stop the error. [Notice: Undefined index: name in C........]
better you have validate this form with java Script. i have attached a snipped part of you form with javascript.
<form action="" method="post" onsubmit="return(Validate());" name="myform">
Name:
<input type="text" name="name">
<span class="error">* <div id="name_error" style="color:red;"></div> </span>
<br><br>
</form>
<script type="text/javascript">
<!--
// Form validation code will come here.
function Validate()
{
if( document.myform.name.value == "" )
{
alert( "Please provide your name!" );
name_error.textContent = "Name is Required.!";
document.myform.name.focus() ;
return false;
}
return( true );
}
//-->
</script>

Issue with simple PHP Contactform

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.

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);

Categories