How to use PHP to make a form send an email? - php

I've been learning PHP for about two days now. So I'm really new to PHP. I have tried my best to understand but no matter what I write, my code never works. I got it to send an email successfully one time. But I'm not able to get it to send the contents in my form.
Here is my HTML form.
<!-- FORM BEGINS -->
<form action="contact-form-handler.php" method="post">
<!-- Full Name -->
<div class="formWrapper ">
<label name="firstname" for="firstName"><span>*</span>First Name</label>
<input type="text" name="memberFirstName" id="memberFirstName" onkeyup="activateButton()" class="inputText" tabindex="1" maxlength="256" onkeydown="return checkAlphaNumericText(event,this);" required="required"/>
</div>
<p class="fieldsetDivider"></p>
<div class="formWrapper">
<label for="lastName"><span>*</span>Last Name</label>
<input type="text" name="memberLastName" id="memberLastName" onkeyup="activateButton()" class="inputText" tabindex="2" maxlength="256" onkeydown="return checkAlphaNumericText(event,this);" required="required"/>
</div>
<p class="fieldsetDivider"></p>
<!-- Date of Birth-->
<p class="fieldsetDivider"></p>
<div class="formWrapper smallInput">
<label for="firstInput"><span>*</span>Date of Birth
<div class="labelClarify">(MM/DD/YYYY)</div>
</label>
<div class="inlineInput">
<input type="text" name="month" id="month" maxlength="2" onkeyup="activateButton();autotab(this, 'day')" onkeypress="return isNumberKey(event)" class="inputText" placeholder="MM" required="required"/>
<span>/</span>
</div>
<div class="inlineInput">
<input type="text" name="day" id="day" maxlength="2" onkeyup="activateButton();autotab(this, 'year')" onkeypress="return isNumberKey(event)" class="inputText" placeholder="DD" required="required"/>
<span>/</span>
</div>
<div class="inlineInput">
<input type="text" name="year" id="year" maxlength="4" onkeyup="activateButton()" onkeypress="return isNumberKey(event)" class="inputText" placeholder="YYYY" required="required"/>
</div>
<a rel="Please enter your date of birth" class="formHelp tooltip-link" href="#">
<img src="../../images/site3/common/form_icon_help.png">
</a>
</div>
<p class="fieldsetDivider"></p>
<!-- Member ID -->
<div class="formWrapper">
<label for="memberID"><span>*</span>Member ID</label>
<div class="inlineInput">
<input type="text" name="memberID" id="memberID" class="inputText" onkeyup="activateButton()" tabindex="3" maxlength="9" onkeypress="return isNumberKey(event)" required="required"/>
</div>
<a rel="Please enter your member ID" class="formHelp tooltip-link" href="#">
<img src="../../images/site3/common/form_icon_help.png">
</a>
</div>
<p class="fieldsetDivider"></p>
<!-- Zip Code -->
<div class="formWrapper">
<label for="zipCode"><span class="requiredStar">*</span>Zip Code</label>
<div class="inlineInput">
<input type="text" name="memberZipCode" id="memberZipCode" onkeyup="activateButton()" tabindex="4" class="inputText" maxlength="5" onkeypress="return isNumberKey(event)"/>
</div>
</div>
<p class="fieldsetDivider"></p>
<!-- Button -->
<div class="button">
<button class="greenBtnLarge" type="submit" style="text-decoration:none;"><span>Next<span></button>
</div>
</form>
<!-- FORM ENDS -->
Can someone please help me with a php code that would work for this form? I have found a couple template forms on the internet and I've spent hours trying to modify them to work with my form. But no luck.
And I can get the PHP and form to work together and make it send me an email from my server, so there's no problem with the server. An email will send. I just can't get the PHP code to send the contents of the form. It sends the email, but with no form details. Understand?
I really, really need help with this. Can you guys help me create a PHP code that will work with my HTML form I posted in this thread? I really need to get past this step in this project.
Thank you!
UPDATE!
Here is PHP template I found on the internet, but I don't know how to really modify it properly.... please help?
<?php
$errors = '';
$myemail = 'example#example.com';//<-----Put Your email address here.
if(empty($_POST['firstname']) ||
empty($_POST['lastname']) ||
empty($_POST['dob']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['firstname'];
$email_address = $_POST['lastname'];
$message = $_POST['dob'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
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' page
header('Location: contact-form-thank-you.html');
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Contact form handler</title>
</head>
<body>
<!-- This page is displayed only if there is some error -->
<?php
echo nl2br($errors);
?>
</body>
</html>

You have a several code errors...
Remove the <label> tags from your titles for <input type="text">... they are not needed.
Make sure your form field name matches your email code $_POST['something'] for example
You have <input type="text" name="memberFirstName" id="memberFirstName" /> in your form... BUT
you have $_POST['firstname'] in your email code. Change $_POST to memberFirstName OR change your <input name and id to firstname
The same changes need to be made to all elements so they match precisely.
AND remember... PHP is case sensitive.

The HTML form fields are not the same with the fields in php email handler
Ex.
The input name should be same as what the handler should get
Since
<input type="text" name="memberFirstName" required="required"/>
The index of $_POST should be same memberFirstName
$_POST['memberFirstName']
This should be applied to all fields
It seems the HTML form is not related to the php handler at all.
Its better to use this form for testing instead
<form action="contact-form-handler.php" method="POST">
First Name: <input name="firstname" type="text"><br>
Last Name:<input name="lastname" type="text"><br>
DOB: <input name="dob" type="text">
<button type="submit">Send</button>
</form>
Note:
If you are using wamp or xampp local server you need to check if the email service is configured correctly otherwise no email will be sent
Check this for reference:
How to configure XAMPP to send mail from localhost?

Related

How to setup contact form for PHP AWS BeanStalk

I have made a website and would like to use AWS to host it. I currently have it running on S3 as a static server however I can't use the contact form for it. So after doing some research I tried AWS beanstalk but can't seem to get it working. When I click submit, nothing happens. This is the code that's setting up the contact form in index.html
<form id="contact-form" action="" class="post-reply" method="POST">
<p><input class="w3-input w3-border" id="form_name" type="text" placeholder="Name" required name="Name"></p>
<p><input class="w3-input w3-border" id="form_number" type="text" placeholder="Phone Number" required name="Phone Number"></p>
<p><input class="w3-input w3-border" id="form_email" type="text" placeholder="Email" required name="Email"></p>
<p><input class="w3-input w3-border" id="form_subject" type="text" placeholder="Subject" required name="Subject"></p>
<p><input class="w3-input w3-border" id="form_message" type="text" placeholder="Message" required name="Message"></p>
</form>
<p>
<button class="w3-button w3-black" type="submit">
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
</p>
Then I created another file and named it mail.php with the following code:
<?php
if (isset($_POST["submit"])) {
$name = $_POST["form_name"];
$email = $_POST["form_email"];
$phone = $_POST["form_phone"];
$subject = $_POST["form_subject"];
$message = $_POST["form_message"];
$to ="duvalprecisiongrinding#gmail.com";
$subject = $subject;
$message = "Email: {$email} Phone: {$phone} Message:" . $message;
//Always set content-type when sending HTML email
$headers ="MIME-Version 1.0" . "\r\n";
//More Headers
$headers .= 'From: duvalprecisiongrinding#gmail.com';
$mail = mail($to,$subject,$message,$headers);
if ($mail) {
echo "<script>alert('Message Sent.');</script>";
}else {
echo "<script>alert('Message not Sent. Please try again.');</script>";
}
}
?>
I made several changes to the contact form that should help, indicated with comments below.
I think the main things keeping it from working at all were the submit button being outside the form and the missing action attribute. Fixing only those would have at least gotten it as far as mail.php, but the names of the form controls need to match the keys of $_POST in mail.php for it to really work as intended.
<form id="contact-form" action="mail.php" class="post-reply" method="POST">
<!-- updated this attribute ^ -->
<p><input class="w3-input w3-border" name="form_name" type="text" placeholder="Name" required></p>
<p><input class="w3-input w3-border" name="form_phone" type="text" placeholder="Phone Number" required></p>
<p><input class="w3-input w3-border" name="form_email" type="text" placeholder="Email" required></p>
<p><input class="w3-input w3-border" name="form_subject" type="text" placeholder="Subject" required></p>
<p><input class="w3-input w3-border" name="form_message" type="text" placeholder="Message" required></p>
<!-- removed the name attributes from the inputs and changed their ids to
names that match the $_POST keys in mail.php -->
<p>
<button class="w3-button w3-black" type="submit" name="submit">
<!-- Moved the button inside the form and added this ^ name attribute -->
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
</p>
</form>

php contact form sending blank emails sometimes

I've gone thru tons of the forms and cant seem to find the answer. I have been working on this problem with my php form on and off for days. hope to find help here. the form is working perfect. all the fields are working correct upon submit, but there always seems to be a second form sent out from a day to two days later that is blank. If there is any suggestions to why this occurs it would be helpful.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
// recipient address
$to = "grandforkssuites#gmail.com";
// subject of email
$re = "Contact Us Form Delivery";
// message creation
$contact = "Name:".$name."\nEmail:".$email."\nSubject:".$subject."\r\n";
$txt = "Comments:".$comments."\r\n";
$fmsg = $contact."\r\n".$txt;
$msg = wordwrap($fmsg, 70);
// send email
mail($to,$re,$msg);
?>
<form action="contact1.php" method=post name="form" id="form">
<div class="col_w280 float_l">
<p><em>
<label for="author">Name:</label> <input type="text" id="name" name="name" class="required input_field" />
<div class="cleaner_h10"></div>
<label for="email">Email:</label> <input type="text" id="email" name="email" class="validate-email required input_field" />
<div class="cleaner_h10"></div>
<label for="email">Phone:</label> <input type="text" id="phone" name="phone" class="required input_field" />
<div class="cleaner_h10"></div>
<label for="subject">Subject:</label> <input type="text" name="subject" id="subject" class="input_field" />
<div class="cleaner_h10"></div>
</div>
<div class="col_w280 float_r">
<label for="text">Comments:</label> <textarea id="comments" name="comments" rows="0" cols="0" class="required input_field"></textarea>
<div class="cleaner_h10"></div></em></p>
<input name=submit type=submit id="submit" onClick="MM_validateForm('name','','R','email','','RisEmail');return document.MM_returnValue" value="Send">
</div></form>
Add validation to the PHP, else even if no values was sent via POST, just by visiting the page its going to send a blank email. Most likely a search engine or such bot is just crawling.
So check its POST
<?php
if($_SERVER['REQUEST_METHOD']==='POST'){
//put code here
}
?>
and check your values are set min-max length ect
<?php
...
...
...
//Comments
if(empty($_POST['comments'])){
//comments empty, do or set something
}else if(strlen($_POST['comments']) < 5){
//not long enough, do or set something
}else if(strlen($_POST['comments']) > 50){
//too large, do or set something
}
?>
and most importantly check email is really an email..
<?php
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
//is an email
}else{
//not an email
}
?>
Also your want to add a basic captcha else your be enjoying 1000s of marketing/spam emails per day.
Good luck, implementing it.

PHP form without opening a new window

Good day/evening. I have this sort of form in HTML:
<form action="scripts/form-testimonial.php" class="form" method="post">
<ul>
<li><label for="name">Name</label> <input class="required" id="namef3" name="name" placeholder="Name" type="text"></li>
<li><label for="email">E-mail</label> <input class="required" id="emailf3" name="email" placeholder="E-mail" type="text"></li>
<li><label for="company">Company</label> <input id="companyf3" name="company" placeholder="Company (if applicable)" type="text"></li>
<li><label for="msg">Message</label> <textarea class="required" cols="43" id="msgf3" name="msg" placeholder="Your feedback" rows="8"></textarea></li>
</ul>
<button class="submit" type="submit">Send your feedback</button>
</form>
and this sort of php sript for this form as a separate file:
<?php
$receip = "office#avehire.co.uk";
$subj = "Testimonial";
$bodymsg = "Name: ".$_POST['name']."\n"
."Company: ".$_POST['company']."\n"
."Email: ".$_POST['email']."\n"
."Message: ".$_POST['msg']."\n";
if(!$_POST['msg']){
header("Location: ../error.html");
exit;
}
$email = $_POST['email'];
if(mail($receip, $subj, $bodymsg, 'From: Contact <'.$email.'>')){
header("Location: ../msg_sent_feedback.html");
}
?>
I also have a validator for this form, but this is not important. What is more important here is the way how this form works. Basically - when you click submit button - it goes to a separate php file, process the form and then - from what is already there - goes to msg_sent_feedback.html file. What I want to do is to NOT opens a separate file but just display a message in the same basic html file where the actual form exists. A message e.g. "Message sent".
Another thing - if I already have a validation script - do I need to have the first "if" in this form? or can I remove it totally? the one which redirects to error.html. Or can I remove these 4 lines? That line - I guess - is responsible for errors in the form, but as I mentioned, I have a validation script. I don't really want to change html. is it possible to modify the php script to work within the html document, as instructed above? thanks
Here is an Jquery ajax example that will help you.
<?php
$receip = "office#avehire.co.uk";
$subj = "Testimonial";
$bodymsg = "Name: ".$_POST['name']."\n"
."Company: ".$_POST['company']."\n"
."Email: ".$_POST['email']."\n"
."Message: ".$_POST['msg']."\n";
if(!$_POST['msg']){
echo "<h1>Error sending e-mail";
exit;
}
$email = $_POST['email'];
if(mail($receip, $subj, $bodymsg, 'From: Contact <'.$email.'>')){
echo "<h1>Email sent successfully</h1>";
}
?>
Html :
<!Doctype html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function submitmyform(){
data=$('#myform').serialize();
$.ajax({
url: "myphpfile.php",
type:'POST',
data:data,
async:false,
dataType:'html',
success: function(msg){
$('#response_goes_here').html(msg);
}
});
}
</script>
<form action="" id="myform">
<ul>
<li> <label for="name">Name</label> <input id="namef3" name="name" type="text" placeholder="Name" class="required"/>
</li>
<li> <label for="email">E-mail</label> <input id="emailf3" name="email" type="text" placeholder="E-mail" class="required"/>
</li>
<li> <label for="company">Company</label> <input id="companyf3" name="company" type="text" placeholder="Company (if applicable)" />
</li>
<li> <label for="msg">Message</label> <textarea id="msgf3" name="msg" cols="43" rows="8" placeholder="Your feedback" class="required"></textarea>
</li>
</ul>
<button type="button" class="button" onclick="submitmyform();">Send your feedback</button>
</form>
<div id="response_goes_here"></div>

Why won't my PHP form send emails correctly?

It sends the email, but without a body, subject or anything. This is what I get:
HTML:
<div class="contact-form">
<form action="mail.php" method="post">
<label for="name">Name:<input type="text" id="name" class="text" /></label>
<label for="email">Email:<input type="text" id="email" class="text" /></label>
<label for="message">Message:<textarea id="message"></textarea></label>
<input type="submit" class="submit" value="Send Message" />
</form>
</div>
PHP (mail.php):
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$recipient = "me#christianselig.com";
$subject = "Message From Website";
$headers = "From: " . $email;
mail($recipient, $subject, $message, $headers);
echo "Thanks! The message was sent. :)";
?>
Any insight? Thanks so much.
Forms fields are based on their names not their ids.
replace your :
id="(...)"
by
id="(...)" name="(...)"
You should have a look to Swift Mailer which is strongly safer than your current method.
You need to have a name attribute on your HTML input fields. That's what the form uses to create the indexes in the $_POST array. Corrected HTML is below
<div class="contact-form">
<form action="mail.php" method="post">
<label for="name">Name:<input type="text" id="name" name="name" class="text" /></label>
<label for="email">Email:<input type="text" id="email" name="email" class="text" /></label>
<label for="message">Message:<textarea id="message" name="message"></textarea></label>
<input type="submit" class="submit" value="Send Message" />
</form>
</div>
you need to give name attribute for each html element . Use below html code:
<div class="contact-form">
<form action="mail.php" method="post">
<label for="name">Name:<input type="text" id="name" name="name" class="text" /></label>
<label for="email">Email:<input type="text" id="email" name="email" class="text" /></label>
<label for="message">Message:<textarea id="message" name="message"></textarea></label>
<input type="submit" class="submit" value="Send Message" />
</form>
</div>
Into my server works, are you sure that in $_POST are set?
If you can't send email assicure you can try to set SMTP to send your email
Try to use something like phpmailer to send email.
In your form for every field you have to put:
- id="example_id"
- name="example_name"

PHP - send two fields through mail

I have a document with 2 textboxes and 1 submit button. I want to send an email when I press the submit button and in it should be the value of the textboxes. My PHP knowledge is a bit dusty. I don't want to bother the user with the emailproces, so he can't see this and should just be redirected.
<html>
<body>
<div class="section_form" id="usernameSection">
<label for="username">Login:</label>
<input size="20" type="text" name="username" id="username" />
</div>
<div class="section_form" id="emailSection">
<label for="email">Email:</label>
<input size="20" type="text" id="email" name="email" maxlength="20"/>
</div>
<div id="submit_button">
<button type="submit" value="Submit" onmouseover="this.style.backgroundPosition='bottom';" onmouseout="this.style.backgroundPosition='top';" onclick="return SetFocus();">Submit</button>
</div>
</body>
</html>
Many thanks!
Use the PHP mail function - listed here.
That should be able to help.
Basically the core of what you're looking for is
<?php
// Check that all fields are present, construct the message body, etc
mail($to, $subject, $body);
header("Location: wherever.php");
exit();
?>
See the mail function in PHP documentation. (Also, thank you Alex for the exit() reminder.)
Use this code for your task.
<?php
if(isset($_POST['submit'])){
extract($_POST);
$message = "username : $username ; email : $email";
$to = "your#email.com";
$subject = "Email Subject";
mail($to, $subject, $message);
}
?>
<html>
<body>
<form method="POST" name="form1">
<div class="section_form" id="usernameSection">
<label for="username">Login:</label>
<input size="20" type="text" name="username" id="username" />
</div>
<div class="section_form" id="emailSection">
<label for="email">Email:</label>
<input size="20" type="text" id="email" name="email" maxlength="20"/>
</div>
<div id="submit_button">
<button type="submit" value="Submit" name="submit" onmouseover="this.style.backgroundPosition='bottom';" onmouseout="this.style.backgroundPosition='top';" onclick="return SetFocus();">Submit</button>
</div>
</form>
</body>
</html>
Start with:
- $_POST
- mail()
Also you need to check: Forms in HTML, you might want to use form to send the data of input fields to server.

Categories