html code:
Contact Me
<label for="Name">Name:</label>
<input type="text" name="name" id="Name" accesskey="N" tabindex="1">
<label for="Email">E-mail:</label>
<input type="text" name="email" id="Email" accesskey="E" tabindex="1">
<label for="Phone">Phone Number:</label>
<input type="text" name="number" id="Number" tabindex="1">
<label for="Comment">Comments</label>
<textarea type="text" name="comment" id="Comment" rows="27" cols="70" tabindex="1"></textarea>
<input id="mySubmit" type="submit" value="Submit">
</form>
</fieldset>
</div>
email.php
<?php
if (isset($_POST['submit'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (!$email)
echo "<script type='text/javascript'>alert('Please enter a valid email address...');history.back();</script>";
else {
$to = "randomemail#gmail.com"; //change this to YOUR email address
$name = (isset($_POST['name'])) ? $_POST['name'] : "anonymous";
$number = (isset($_POST['number'])) ? $_POST['number'] : "none";
$comment = (isset($_POST['comment'])) ? $_POST['comment'] : "none";
$subject = "Message from $name via contact form";
$message = "Name: $name\nNumber: $number\nEmail: $email\nMessage: $comment";
$from = "From: " . $name . "<" . $email .">\r\n" .
"Reply-To: " . $email ."\r\n" .
"X-Mailer: PHP/" . phpversion();
if (mail($to, $subject, $message, $from))
header("Location: thanks.html");
else
echo "<script type='text/javascript'>alert('An unknown system error has occurred!');history.back();</script>";
}
}
?>
when you submit, it loads email.php, but only a white page, not the thanks.html that it should.
You forgot to name your submit field:
<input id="mySubmit" type="submit" value="Submit" name="submit">
^^^^^^^^^^^^^
Don't use form fields to detect a post. Use the 100% reliable:
if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }
instead. This will ALWAYS be true if a POST was performed. As you can see with your version, a simple typo or oversight will completely kill your logic.
First Empty your file and just put header("Location: thanks.html"); in your php tags. If it works then add the other lines progressively. you'll see the annoying line. Read about header on PHP reference website. It should be used carefully
Related
I've used the folowing step by step guide:
http://acmeextension.com/integrate-google-recaptcha-with-php/.
But for some reason, the recaptcha doesnt call/show up on the site?
I've called the script in the footer using:
<script src='https://www.google.com/recaptcha/api.js' async defer >
I've tried putting the PHP code right above the email form but it still didn't work. So, I separated it and put it into the separate send_form_email.php page.
This is the email form in which I implemented the recaptcha:
<form name="contactform" method="post" action="send_form_email.php" class="mb-0">
<div class="row">
<div class="col-md-6">
<input type="text" class="form-control" name="first_name" maxlength="50" placeholder="First Name: *" required>
</div>
<div class="col-md-6">
<input type="text" class="form-control" name="last_name" maxlength="50" size="30" placeholder="Last Name:">
</div>
<div class="col-md-6">
<input type="text" class="form-control" name="telephone" maxlength="50" placeholder="Phone:">
</div>
<div class="col-md-6">
<input type="email" class="form-control" name="email" maxlength="80" placeholder="Email: *" required>
</div>
<div class="col-md-12">
<textarea class="form-control" name="comments" rows="3" maxlength="1000" placeholder="Message: *" required></textarea>
</div>
<div class="g-recaptcha col-md-12" data-sitekey="6LexIpoUAAAAAMMftZIWNkik8IqsLfZDCKQxO9XO"></div>
<div class="col-md-12">
<input type="submit" value="Send Now" name="Submit" class="btn btn--secondary btn--rounded">
</div>
</div>
</form>
This is the sendemail php file:
<?php
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "[REMOVED]";
$email_subject = "Emailed from Webform";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
{
$secret = '[REMOVED]';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success)
{
$succMsg = 'Your contact request have submitted successfully.';
}
else
{
$errMsg = 'Robot verification failed, please try again.';
}
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
<p>Thank you for contacting us. We will be in touch with you very soon.</P>
<?php
}
?>
It should show recpatcha code according to the tutorial. In reality it doesn't.
I had a normal site that I built with custom HTML/CSS/JS. I changed the site to become a WordPress site (and made my custom html/css/js into a custom WordPress theme). I had a contact form on the homepage of the site, which broke when I made the change to WordPress.
When the form was functioning, it would refresh the page and bring the user back down to the form (using the anchor id=contactphilly) and then the user would see a message confirming their email was sent.
I did a LOT of Googling and I think it has something to do with the "action" option in the form, but no matter what I try changing it to, it doesn't work. I tried the following for the action value:
<?php the_permalink(); ?>/#contactphilly
#contactphilly
<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>
$_SERVER['REQUEST_URI']
None of them worked.
Here is the code for the form:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'WebKeep.com';
$to = 'info#webkeepteam.com';
$subjectemail = 'Message from WebKeepTeam.com Contact Form ';
$body = "From: $name\n E-Mail: $email\n Subject: $subject\n Message:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage) {
if (mail ($to, $subjectemail, $body, $from)) {
$result='<div>Thank You! We will respond shortly.</div>';
} else {
$result='<div>Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
and
<form name="contactform" method="post" action="#contactphilly">
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<fieldset class="form-group">
<input type="text" value="<?php echo $name;?>" class="form-control transparent-input" id="name" name="name" placeholder="Name">
</fieldset>
<?php echo "<p class='text-danger'>$errName</p>";?>
<fieldset class="form-group">
<input type="email" value="<?php echo $email;?>" class="form-control transparent-input" id="email" name="email" placeholder="Email">
</fieldset>
<?php echo "<p class='text-danger'>$errEmail</p>";?>
<fieldset class="form-group">
<input type="text" class="form-control transparent-input" value="<?php echo $subject;?>" id="subject" name="subject" placeholder="Subject">
</fieldset>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<fieldset class="form-group">
<textarea class="form-control transparent-input" id="message" value="<?php echo $message;?>" name="message" rows="6" placeholder="Message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
</fieldset>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-index pull-right">
</div>
<?php echo $result; ?>
</form>
I found an answer to my own question! I completely forgot about this bit of code on GitHub: https://github.com/dwyl/html-form-send-email-via-google-script-without-server I used it elsewhere on the site and it worked, and it also works beautifully for forms within pages too!
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I have very limited knowledge. I tried my best to understand. I want to send mail from a contact form, upon success show an alert message and remain on the same page. the mail is not sending and seems likeI have some bugs in the code. kindly help.
<form action="" method="post">
<div class="col-md-6">
<input name="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="col-md-6">
<input name="email" type=“text” class="form-control" placeholder="Email">
</div>
<div class="col-md-12">
<input name="subject" type="text" class="form-control" placeholder="Subject">
</div>
<div class="col-md-12">
<textarea name="message" class="form-control" placeholder="Message" rows="4"></textarea>
</div>
<div class="col-md-8">
<input type="submit" class="form-control text-uppercase" name="send" value="submit" />
</div>
</form>
<?php
if ($_POST['send']) {
$ToEmail = 'info#autonomousdata.com';
$EmailSubject = $_POST['subject'];
$mailheader = "From: ".$_POST['email']."\r\n";
$mailheader .= "Reply-To: ".$_POST['email']."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n" .
"X-Mailer: PHP/" . phpversion();
$MESSAGE_BODY = "Name: ".$_POST['name']."\n";
$MESSAGE_BODY .= "Email: ".$_POST['email']."\n";
$MESSAGE_BODY .= "Comment: ".$_POST['message']."";
if(mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader)!==true) {
?>
<script type='text/javascript'> alert('failed to send the mail'); </script>
<?php
die('Fail to send');
} else{
?>
<script type='text/javascript'>alert('Thank you for contacting us! All information received will always remain confidential. We will contact you as soon as we review your message.');
</script>
<?php
}
}
?>
The HTML form had dubious quotation marks around the type='text' and I modified the php to add some rudimentary checking of variables and also sanitisation ~ hope it will help.
<form action="" method="post">
<div class="col-md-6">
<input name="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="col-md-6"><!-- // incorrect quotation used on `text` //-->
<input name="email" type='text' class="form-control" placeholder="Email">
</div>
<div class="col-md-12">
<input name="subject" type="text" class="form-control" placeholder="Subject">
</div>
<div class="col-md-12">
<textarea name="message" class="form-control" placeholder="Message" rows="4"></textarea>
</div>
<div class="col-md-8">
<input type="submit" class="form-control text-uppercase" name="send" value="submit" />
</div>
</form>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['subject'],$_POST['email'],$_POST['name'],$_POST['message'] ) ){
$to = 'info#autonomousdata.com';
$name = filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING );
$subject = filter_input( INPUT_POST, 'subject', FILTER_SANITIZE_STRING );
$message = filter_input( INPUT_POST, 'message', FILTER_SANITIZE_STRING );
$email = filter_var( filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING ), FILTER_VALIDATE_EMAIL );
$headers=array();
$headers[]="From: {$email}";
$headers[]="Reply-To: {$email}";
$headers[]="Content-type: text/html; charset=iso-8859-1";
$headers[]="X-Mailer: PHP/" . phpversion();
/* generate final headers string */
$headers=implode( "\r\n", $headers );
$message=array();
$message[]="Name: {$name}";
$message[]="Email: {$email}";
$message[]="Comment: {$message}";
/* generate final message string */
$message=implode( "\n", $message );
$result=#mail( $to, $subject, $message, $headers );
switch( $result ){
case true:
$msg='Thank you for contacting us! All information received will always remain confidential. We will contact you as soon as we review your message.';
break;
case false:
$msg='failed to send the mail';
break;
}
echo "<script type='text/javascript'>alert('{$msg}');</script>";
}
?>
The test page, in it's entirety, that I set up to test the basic functionality of the script. As this was all run locally I cannot confirm whether the email would be sent - it looks correct however.
<?php
?>
<!doctype html>
<html>
<head>
<title>Basic Contact Form - investigating email send failure.</title>
<script type='text/javascript' charset='utf-8'></script>
<style type='text/css' charset='utf-8'>
form{
width:50%;
}
form,output,input[type='text'],textarea,input[type='button'],input[type='submit']{
display:block;
box-sizing:border-box;
padding:0.5rem;
margin:0.5rem;
}
output{
color:red;
}
input[type='text'],textarea{
width:60%;
}
</style>
</head>
<body>
<form action="" method="post">
<div class="col-md-6">
<input name="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="col-md-6"><!-- // incorrect quotation used on `text` //-->
<input name="email" type='text' class="form-control" placeholder="Email">
</div>
<div class="col-md-12">
<input name="subject" type="text" class="form-control" placeholder="Subject">
</div>
<div class="col-md-12">
<textarea name="message" class="form-control" placeholder="Message" rows="4"></textarea>
</div>
<div class="col-md-8">
<input type="submit" class="form-control text-uppercase" name="send" value="submit" />
</div>
<output id='msgs'></output>
</form>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['subject'],$_POST['email'],$_POST['name'],$_POST['message'] ) ){
$to = 'info#autonomousdata.com';
$name = filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING );
$subject = filter_input( INPUT_POST, 'subject', FILTER_SANITIZE_STRING );
$message = filter_input( INPUT_POST, 'message', FILTER_SANITIZE_STRING );
$email = filter_var( filter_input( INPUT_POST, 'email', FILTER_SANITIZE_STRING ), FILTER_VALIDATE_EMAIL );
if( !$to or !$name or !$subject or !$message or !$email ){
echo "Error: one or more required variables are not available.";
} else {
$headers=array();
$headers[]="From: {$email}";
$headers[]="Reply-To: {$email}";
$headers[]="Content-type: text/html; charset=iso-8859-1";
$headers[]="X-Mailer: PHP/" . phpversion();
/* generate final headers string */
$headers=implode( "\r\n", $headers );
$message=array();
$message[]="Name: {$name}";
$message[]="Email: {$email}";
$message[]="Comment: {$message}";
/* generate final message string */
$message=implode( "\n", $message );
$result=#mail( $to, $subject, $message, $headers );
switch( $result ){
case true:
$msg='Thank you for contacting us! All information received will always remain confidential. We will contact you as soon as we review your message.';
break;
case false:
$msg='Failed to send the mail';
break;
}
/* Let the user know the status of the form submission somehow */
echo "
<script type='text/javascript'>
document.getElementById('msgs').innerHTML='{$msg}';
/*
alert('{$msg}');
*/
</script>";
}
}
?>
</body>
</html>
I purchased a theme, and I need to make a processing.php for my contact form. The form that sends the data to the server for processing.
This is the form code:
<div class="form_error text-center">
<div class="name_error hide error">Please Enter your name</div>
<div class="email_error hide error">Please Enter your Email</div>
<div class="email_val_error hide error">Please Enter a Valid Email Address</div>
<div class="message_error hide error">Please Enter Your Message</div>
</div>
<div class="Sucess"></div>
<form role="form">
<div class="row">
<div class="col-md-4">
<input type="text" class="form-control" id="name" placeholder="Name">
<input type="email" class="form-control" id="email" placeholder="Email">
<input type="text" class="form-control" id="subject" placeholder="Subject">
</div>
<div class="col-md-8">
<textarea class="form-control" id="message" rows="25" cols="10" placeholder=" Message Texts..."></textarea>
<button type="button" class="btn btn-default submit-btn form_submit">SEND MESSAGE</button>
</div>
</div>
</form>
Both shubham and adi's answers are vulnerable to SMTP header injections, allowing your contact form to be used to send spam. It will happen.
Any POST or GET data passed to the additional_headers parameter needs to be sanitised to prevent abuse.
See the following:
http://php.net/manual/en/function.mail.php
https://www.phpsecure.info/v2/article/MailHeadersInject.en.php
see this example
<?php
if(isset($_POST['submit'])){
$to = "email#example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
if (isset($_POST['contact_name'])&&isset($_POST['contact_mail'])&&isset($_POST['message'])) {
$contact_name = $_POST['contact_name'];
$contact_mail = $_POST['contact_mail'];
$message = $_POST['message'];
if (!empty($contact_name) && !empty($contact_mail) && !empty($message)) {
$to = 'your email#gmail.com'; // this is where you want to send the email
$subject = 'Contact form Submitted';
$body = $contact_name."\n".$message;
$headers = 'From:'.$contact_mail; // email of the sender
if (#mail($to, $subject, $body, $headers)) {
echo 'Thanks for contacting us';
}
else {
echo 'Sorry, an error has been occurred';
}
}
else {
echo 'All fields are required';
}
}
?>
<form action="index.php" method="POST">
Name:<br>
<input type="text" name="contact_name"></input><br><br>
Email Address:<br>
<input type="text" name="contact_mail"></input><br><br>
Message:<br>
<textarea name="message" cols="30" rows="6"></textarea><br><br>
<input type="submit" value="Send"></input>
</form>
maybe this codes can help you
After searching for about 3 hours i still can't figure this one out.
I Have a html template with a contact form and im trying to make it work using a PHP script.
I changed the template to PHP and pasted the PHP form script in it. everything is working fine except the confirmation text.
After a successful submission it will just refresh the page instead of printing "Your mail has been sent successfuly ! Thank you for your feedback". i do not want a redirect, i just want it to print on the same page.
Any ideas?
I got a sample of my code.
<form action="<? echo $_SERVER['PHP_SELF']; ?>" id="contact-form" method="post" class="form afsana-form" role="form">
<div class="row">
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="name" name="name" placeholder="name" type="text" required autofocus />
</div>
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="email" name="email" placeholder="email" type="email" required />
</div>
<div class="col-sm-12 form-group">
<textarea class="form-control" id="message" name="message" placeholder="message" rows="5"></textarea>
</div>
<div class="col-sm-12 form-group">
<button class="btn btn-primary afsana-btn" name="submit" value="verzenden" type="submit">Verzenden <i class="ion-arrow-graph-up-right"></i></button>
</div>
</div>
</form>
<?php
if(isset($_POST["submit"])){
// Checking For Blank Fields..
if($_POST["name"]==""||$_POST["email"]==""||$_POST["message"]==""){
echo "Fill All Fields..";
}else{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['email'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email){
echo "Invalid Sender's Email";
}
else{
$subject = (Contact_form);
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$headers .= 'Cc:'. $email2 . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// Send Mail By PHP Mail Function
mail("something#domain.com", $subject, $message, $headers);
echo "Your mail has been sent successfuly ! Thank you for your feedback";
}
}
}
?>
First, you have this: $subject = (Contact_form); which should throw an error, so I assume you have error reporting turned off. When developing, you should have error reporting on so you can see errors in your code... Else you are just working blind. I don't mean by throwing tacky error_reporting(0) in every file either, I mean to set your error reporting level to E_ALL in your php.ini.
You also have: $headers .= 'Cc:'. $email2 . "\r\n";
However, $email2 is not defined anywhere, so you would get an error here too.. which is why it's important to test with error reporting on.
See if this works:
<?php
$error = '';
if(isset($_POST['submit']))
{
if ( !empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message']) )
{
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if ( $email = filter_var($email, FILTER_VALIDATE_EMAIL) )
{
$subject = '(Contact_form)';
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$message = wordwrap($message, 70);
if ( $result = mail("something#domain.com", $subject, $message, $headers) ) {
$error = 'Success';
} else {
$error = 'There was an error sending your email!';
}
} else {
$error = 'Invalid Email Address!';
}
} else {
$error = 'Please fill all fields.';
}
}
?>
<p><?= $error ?></p>
<form action="" method="post">
<input type="text" name="name" value="" /><br />
<input type="email" name="email" value="" /><br />
<textarea name="message" rows="5"></textarea><br />
<input type="submit" name="submit" value="submit" />
</form>
Try to put in $subject just a string value like:
$subject = 'Test subject';
change also the following line to this (there is no $email2 defined):
$headers .= 'Cc:'. $email . "\r\n"; // Carbon copy to Sender
and give it a try. You can also put as first line of your code
<?php error_reporting(E_ALL); ?>
and check for errors when submiting the form.