There's a lot of blank php email posts on here but none of them have solved this for me.
I tweaked this simple php code I found to simply email a specified email address (in this case, my client's email) with a feedback message from a customer on their website. Through testing, I could only get it to send emails when I didn't include the initial if statement as validation, but even then, the emails would have no subject or body.
contact.html
<form name="feedback" class="form-horizontal" role="form" action="send_form_email.php" method="post">
<div class="form-group">
<label for="inputName" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="inputName" placeholder="Name"><br />
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control" name="inputEmail" placeholder="Email"><br />
</div>
</div>
<div class="form-group">
<label for="inputMessage" class="col-sm-3 control-label">Message</label>
<div class="col-sm-9">
<textarea type="text" class="form-control" name="inputMessage" placeholder="Message"></textarea><br />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input class="btn btn-default" type="submit" value="Submit">
</div>
</div>
</form>
send_form_email.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Contact subject
$name =$_POST['inputName'];
// Details
$message=$_POST['inputMessage'];
// Mail of sender
$mail_from=$_POST['inputEmail'];
// From
$header="from: $name <$mail_from>";
// Enter your email address
$to ='test#gmail.com';
$send_contact=mail($to,$name,$message,$header);
// Check, if message sent to your email
// display message "We've recived your information"
header("Location: http://wetzelscontracting.com/postcontact.html");
if($send_contact){
echo "We've recived your contact information";
}
else {
echo "ERROR";
}}
?>
Ok guys, long story, but Mailto isn't actually in the action attr, I removed it from the post.
Actually, I don't know what kind of frankenstein code I originally posted, but that was full of errors that are no longer there. Hopefully I posted the right code this time.
Why is your form action MAILTO:?
<form name="feedback" class="form-horizontal" role="form" action="MAILTO:send_form_email.php" method="post">
It should just be a clean call to the PHP page like this:
<form name="feedback" class="form-horizontal" role="form" action="send_form_email.php" method="post">
The only time you would use MAILTO: is when constructing an <a href="mailto:someguy#someplace.somedomain">. For an HTML form using PHP like this the goal is to submit the form, and the the $_POST data gets parsed by the PHP which then acts on it to send an e-mail.
Additionally, you are not setting name values in any of the input fields & the names you have for id values dont even match what the PHP is attempting to do. So try this for the HTML:
<form name="feedback" class="form-horizontal" role="form" action="send_form_email.php" method="post">
<div class="form-group">
<label for="inputName" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputName" placeholder="Name" name="inputName"><br />
</div></div>
<div class="form-group">
<label for="inputEmail" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="Email" name="inputEmail"><br />
</div></div>
<div class="form-group">
<label for="inputMessage" class="col-sm-3 control-label">Message</label>
<div class="col-sm-9">
<textarea type="text" class="form-control" id="inputMessage" placeholder="Message" name="inputMessage"></textarea><br />
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input class="btn btn-default" type="submit" value="Submit">
</div></div>
</form>
Also here is the reworked PHP code.
The first thing I did was take all of your $_POST checks into a structure that uses one main array ($post_array) and then rolls through that array to process the values & assign them to similarly named variables. You had absolutely no input validation before. This is technically not even really great “validation” since isset() just checks to see if the $_POST value even exists. But this is step up.
Also I reworked your error checking logic at the end since it all happened after headers were sent. Meaning none of that the whole "We've recived your information" would never work. This is the best I can do with the info you’re providing, but I am doing this to convey the basic concepts:
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST"){
// Set the post values array.
$post_array = array('inputName','inputEmail','inputMessage');
// Roll through the post values array.
foreach($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_key] ? $_POST[$post_key] : null;
}
// From
$header="from: $name <$mail_from>";
// Enter your email address
$to ='test#gmail.com';
$send_contact=mail($to,$name,$message,$header);
// Check, if message sent to your email
// display message "We've recived your information"
if($send_contact){
header("Location: http://wetzelscontracting.com/postcontact.html");
}
else {
echo "ERROR";
}
}
?>
As none of the other answers have covered the issue of validation apart from the one accepted, but if your going to do that you might as well just use the extract() function, (it also won’t protect from header injection or email validation).
It’s very important to validate user input and a layer of simple CSRF protection, else bots or spammers can directly POST to your PHP and it will send you a bombardment of emails, you won’t see the forest for the trees (legit emails), or worse inject headers into your inputEmail field and send their own emails using your server which is obviously something you don't want to happen.
Also I’ve added an easy way that you can pass errors from your PHP script that sends the user back to the form for you to echo out.
So for the send_form_email.php file.
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_SESSION['csrf'])){
//set error array to fill
$errors = array();
// Validate Contact subject
if(!empty($_POST['inputName'])){
$name = $_POST['inputName'];
}else{
$error['inputName'] = 'Required!';
}
// Validate Details
if(!empty($_POST['inputMessage'])){
$message = $_POST['inputMessage'];
}else{
$error['inputMessage'] = 'Required!';
}
// Validate Mail of sender
if(!empty($_POST['inputEmail'])){
if(filter_var($_POST['inputEmail'], FILTER_VALIDATE_EMAIL)){
$mail_from = $_POST['inputEmail'];
}else{
$error['inputEmail'] = 'Invalid Email!';
}
}else{
$error['inputEmail'] = 'Required!';
}
if(!isset($_POST['csrf']) || $_SESSION['csrf'] != $_POST['csrf']){
$_SESSION['email_status'] = 'Invalid csrf token!';
$error = true;
}
//stop multiple attempts - just remove csrf token
unset($_SESSION['csrf']);
//no errors send mail
if(empty($error)){
$headers ='MIME-Version: 1.0'."\r\n";
$headers.='Content-type: text/html; charset=utf8'."\r\n";
$headers.='From:<'.$mail_from.'>'."\r\n";
$headers.="X-Mailer: PHP"."\r\n";
if(mail('test#gmail.com', 'Website email form: '.$name, $message, $headers)){
$_SESSION['email_status'] = "We've received your contact information";
//send to success page
exit(header("Location: http://wetzelscontracting.com/postcontact.html"));
}else {
$_SESSION['email_status'] = 'There was an error sending the mail';
//backup to file
file_put_contents('mail.log.txt',print_r($_POST, true).PHP_EOL, FILE_APPEND);
}
}else{
//assuming its this url
exit(header("Location: http://wetzelscontracting.com/contact.php"));
$_SESSION['email_error'] = $error;
}
}else{
//stop multiple attempts
unset($_SESSION['csrf']);
//dont allow GET request/direct access
exit(header("Location: http://wetzelscontracting.com/contact.php"));
}
?>
Then in your page with the form, start a session to read from the $_SESSION array, and then echo out your errors if any.
<?php
session_start();
//make a session key that we will check against in send_form_email.php
$_SESSION['csrf'] = sha1(uniqid(true));
?>
<?php echo isset($_SESSION['email_status']) ? $_SESSION['email_status'] : null ?>
<form name="feedback" class="form-horizontal" role="form" action="send_form_email.php" method="post">
<input type="hidden" name="csrf" value="<?php echo $_SESSION['csrf'];?>"/>
<div class="form-group">
<label for="inputName" class="col-sm-3 control-label">Name <?php echo isset($_SESSION['email_error']['inputName']) ? $_SESSION['email_error']['inputName'] : null?></label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputName" placeholder="Name" name="inputName"><br />
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-3 control-label">Email <?php echo isset($_SESSION['email_error']['inputEmail']) ? $_SESSION['email_error']['inputEmail'] : null?></label>
<div class="col-sm-9">
<input type="email" class="form-control" id="inputEmail" placeholder="Email" name="inputEmail"><br />
</div>
</div>
<div class="form-group">
<label for="inputMessage" class="col-sm-3 control-label">Message <?php echo isset($_SESSION['email_error']['inputMessage']) ? $_SESSION['email_error']['inputMessage'] : null?></label>
<div class="col-sm-9">
<textarea type="text" class="form-control" id="inputMessage" placeholder="Message" name="inputMessage"></textarea><br />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input class="btn btn-default" type="submit" value="Submit">
</div>
</div>
</form>
<?php
//unset the errors so there only shown once
unset($_SESSION['email_status']);
unset($_SESSION['email_error']); ?>
Related
I never used PHP before, but I need to set up an HTML form from to be sent from my website to my gmail account. Checked some tutorials and came up with this code. But for some reason it is not working. When I hit submit it goes to a "Page Not Found
Looks like you've followed a broken link or entered a URL that doesn't exist on this site." Not sure what am I doing wrong.
I have my HTML document, and I have my PHP document. Saved together.
<form action="contact.php" method="POST" name="form">
<div class="row">
<div class="col-12 col-md-6">
<div class="contact-form">
<label for="name">Please enter your name:</label>
<input name="name" type="text" class="form-control" placeholder="Harry Potter">
</div>
</div>
<div class="col-12 col-md-6">
<div class="contact-form">
<label for="mail">Your email address:</label>
<input name="mail" type="email" class="form-control" placeholder="harry#potter.com">
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="contact-form">
<label for="message">How can I help you?</label>
<textarea name="message" class="form-control" id="form-text" cols="30" rows="10" placeholder="Let's do some magic"></textarea>
</div>
</div>
</div>
<div id="submit" class="text-center">
<button name="submit" type="submit" class="btn mt-5 mx-auto">Submit</button>
</div>
</form>
<?php
if(isset($_POST["submit"])) {
$name=$_POST["name"];
$mailFrom=$_POST["mail"];
$message=$_POST["message"];
$mailTo = "myaddress#gmail.com";
$subject = "Form from my website";
$headers = "From: ".$mailFrom;
$txt = "You have received an e-mail from ".$name."\n\n".$message;
if(mail($mailTo, $subject, $txt, $headers)) {
echo "<h1>I recieved your email! Will be in touch with you soon.</h1>";
}
else{
echo "<h1>Something went wrong! Try again.</h1>";
}
header("Location: https://www.whatever.com");
}
?>
New to php, would appreciate your help with this:
I made a signup form script to validate the user's input via multiple error handlers. (check valid email, pwd and pwd re-entry match etc).
In case the user filled all fields but one had an error (failed to pass the error handler), i wanted to send back the other fields to the same form so the user doesn't have to refill'm all over again. So if the passwords dint match, i wanted to reload the same page but with the other filed filled.
i can see the information in the url of the page but not in the form fields.
below my form HTML
<div class="register-content">
<form action="includes/signup.inc.php" method="POST" class="margin-bottom-0">
<label class="control-label">Name <span class="text-danger">*</span></label>
<div class="row row-space-10">
<div class="col-md-6 m-b-15">
<input type="text" name="uFirst" class="form-control" placeholder="First name" required />
</div>
<div class="col-md-6 m-b-15">
<input type="text" name="uLast" class="form-control" placeholder="Last name" required />
</div>
</div>
<label class="control-label">Username <span class="text-danger">*</span></label>
<div class="row m-b-15">
<div class="col-md-12">
<input type="text" name="uName" class="form-control" placeholder="Username" required />
</div>
</div>
<label class="control-label">Email <span class="text-danger">*</span></label>
<div class="row m-b-15">
<div class="col-md-12">
<input type="text" name="mail" class="form-control" placeholder="Email address" required />
</div>
</div>
<label class="control-label">Password <span class="text-danger">*</span></label>
<div class="row m-b-15">
<div class="col-md-12">
<input type="password" name="pwd" class="form-control" placeholder="Password" required />
</div>
</div>
<label class="control-label">Re-enter Password <span class="text-danger">*</span></label>
<div class="row m-b-15">
<div class="col-md-12">
<input type="password" name="pwd-repeat" class="form-control" placeholder="Re-enter Password" required />
</div>
</div>
Below my php code
<?php if(isset($_POST['signup-submit'])) {
require 'dbh.inc.php';
$firstName=$_POST['uFirst'];
$lastName=$_POST['uLast'];
$userName=$_POST['uName'];
$email=$_POST['mail'];
$password=$_POST['pwd'];
$passwordRepeat=$_POST['pwd-repeat'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("location: ../signup.php?error=invalidemail&uid&uFirst=".$firstName."&uLast=".$lastName);
exit();
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("location: ../signup.php?error=invalidemail&uFirst=".$firstName."&uLast=".$lastName."&uName=".$userName);
exit();
} else if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("location: ../signup.php?error=invaliduid&uFirst=".$firstName."&uLast=".$lastName."&mail=".$email);
exit();
} else if ($password !== $passwordRepeat) {
header("location: ../signup.php?error=passwordnotmatching&uFirst=".$firstName."&uLast=".$lastName."&uName=".$userName."&mail=".$email);
exit();
?>
There are several ways to address this. Ultimately, there are two high-level options:
Pass the valid values back into the new form
Never remove the valid values(i.e. JavaScript + AJAX)
With your current setup, (1) would be simpler. To work with your current design, you would need to store the values somewhere to pass back to the form to render. The simplest would be to add them to the URL parameters(query string), but other options include cookies or session storage.
The simplest option would be to combine your form and validation into a single endpoint rather than separating them. That way, you already have the post data when rendering the form with the error messages.
Once you have the values, you can simply insert them into the form HTML with the value attribute(be sure to HTML encode(htmlentities) any user input values to avoid XSS vulnerabilities).
For example:
<input type="text" name="uFirst" class="form-control" placeholder="First name" value="<?= htmlentities($firstName) ?>" required />
I just noticed(from one of the comments) that you are already passing your valid values in the query string with your existing redirect. In that case, you can simply do something like this:
<input type="text" name="uFirst" class="form-control" placeholder="First name" value="<?= htmlentities($_GET["uFirst"]??"") ?>" required />
Encoding the values is very important. Not properly encoding values, especially from user input, can allow malicious users to craft values that break out of your HTML and alter the page, a vulnerability known as Cross-Site Scripting(or XSS, for short).
I am unable to configure my email address on the submit button in this piece of code:
<div id="contact" class="spacer">
<div class="container contactform center">
<h2 class="text-center wowload fadeInUp">Get in touch with us</h2>
<div class="row wowload fadeInLeftBig">
<div class="col-sm-6 col-sm-offset-3 col-xs-12">
<form class="cmxform" id="commentForm" method="post" action="email.php">
<fieldset>
<input type="text" placeholder="Subject" id="csubject" name="subject" minlength="2" type="text" required>
<input type="text" placeholder="Email" id="cemail" type="email" name="email" required>
<textarea rows="5" placeholder="Message" id="ccomment" name="comment" required></textarea>
<input class="submit btn btn-primary" type="submit" value="Submit">
</fieldset>
</form>
</div>
</div>
I tried linking it to a php page (email.php), but it says server error. I don't know what to do. Can someone please help me?
To send an email you need the mail() function http://php.net/manual/en/function.mail.php
With your code you need to name the submit like name="submit" then inside action.php file you have to write something like this (or inside the same php where you have this code):
if(isset($_POST["submit"]))
{
//Remember to do input validations
$subject = $_POST["subject"];
$from = $_POST["email"];
$comment = $_POST["comment"];
$body = "User with email $from send the next comment: $comment";
//then here you set your email
$to = "myemail#email.com"; //change this
mail($to,$subject,$body);
}
This is only to explain some basic usage and set the variables you need, I advice you read also PHPmailer class
I'm redesigning a site, and having just uploaded the files to the host, am now testing that everything works. The message form is not working consistently - sometimes it sends the user to the thank you confirmation page and sometimes it displays the error: "500 Internal Server Error, The server encountered an internal error or misconfiguration and was unable to complete your request." However, no test email has arrived at the recipient address showing that the form has worked. Strangely, it successfully went through when I substituted my personal email address in the mailer.php document. This makes me think that the code works.
I'm suspecting that this is a server or email configuration issue, because I've also been having issues with email, after changing hosts, but possibly it has to do with my code?
HTML:
<form class="form-horizontal" method="post" action="mailer.php" class="form-horizontal" role="form">
<div class="form-group">
<label for="name" class="col-sm-2"><small>Name</small></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputName" name="inputName" placeholder="Enter your full name" required>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2"><small>Email</small></label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Enter your email, example#domain.com" required>
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2"><small>Telephone</small></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPhone" name="inputPhone" placeholder="Enter your telephone number" required>
</div>
</div>
<div class="form-group">
<label for="message" class="col-sm-2"><small>Message</small></label>
<div class="col-sm-10">
<textarea class="form-control" rows="4" name="inputMessage" id="inputMessage" placeholder="Enter your message here" required></textarea>
</div>
</div>
<div class="form-group">
<!-- The following field is for robots only, invisible to humans: -->
<p class="robotic" id="pot">
<label>If you're human leave this blank:</label>
<input name="robotest" type="text" name="robotest" id="robotest" class="robotest" />
</p>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input style="font-size:22px;" id="submit" name="submit" type="submit" value="Send" class="btn">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<! Will be used to display an alert to the user>
</div>
</div>
</form>
mailer.php file:
<?php
/* Set e-mail recipient */
$myemail = "info#domain.com";
/* Check all form inputs using check_input function */
$name = check_input($_POST['inputName'], "Your name was not entered correctly.");
$email = check_input($_POST['inputEmail'], "Your email address was not entered correctly.");
$phone = check_input($_POST['inputPhone'], "Your telephone number was not entered correctly.");
$message = check_input($_POST['inputMessage'], "Your message was not entered correctly.");
$robotest = $_POST['robotest'];
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Invalid e-mail address.");
}
/* ROBOT TEST */
if($robotest)
{
show_error("Denied, robot.");
}
/* prepare the message for the e-mail */
$subject = "Inquiry from Website";
$message = "
Someone has sent you a message using your website's contact form:
Name: $name
Email: $email
Telephone: $phone
Subject: $subject
Message:
$message
";
/* send the message using mail() function */
mail($myemail, $subject, $message);
/* redirect visitor to the thank you page */
header('Location: http://www.website.com/thankyou.html');
exit();
/* functions used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again.</p>
</body>
</html>
<?php
exit();
}
?>
It appears you have a server/configuration problem. I've used this code and put it on my own server and it works perfectly fine. (also, nice work, very clean code)
One thing to think about when checking whether you get emails or not (specifically when a personal email works, but a corporate one does not) is email heuristics. Try changing the content setup and/or the subject line. (the subject line looks suspcious to me, I'd start there).
https://en.wikipedia.org/wiki/Naive_Bayes_spam_filtering
I have a simple form with 3 fields, contact_name contact_email & contact_message when i submit this, the data entered into the form is not emailed to me. however if i check what is being posted i can see an array is posted:
Array
(
[contact_name] => paul
[contact_email] => test#test.com
[contact_message] => D;LKF'DSKF;LSDKF
)
Here is my form code:
<form role="form" name="form1" action="send_form_email.php" method="post">
<div class="row">
<div class="form-group col-xs-12 floating-label-form-group">
<label for="name">Name</label>
<input class="form-control" type="text" name="contact_name" placeholder="Name" id="contact_name">
</div>
</div>
<div class="row">
<div class="form-group col-xs-12 floating-label-form-group">
<label for="email">Email Address</label>
<input class="form-control" type="email" name="contact_email" placeholder="Email Address" id="contact_email">
</div>
</div>
<div class="row">
<div class="form-group col-xs-12 floating-label-form-group">
<label for="message">Message</label>
<textarea name="contact_message" placeholder="Message" class="form-control" rows="5" id="contact_message"></textarea>
</div>
</div>
<br>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-lg btn-success">Send</button>
</div>
</div>
</form>
And here is the php script:
<?php
// Contact subject
$subject ='Message from Leeds Computers';
// Details
$message="$contact_message";
// Mail of sender
$mail_from="$contact_email";
// From
$header="from: $contact_name <$mail_from>";
// Enter your email address
$to ='test#gmail.com';
$send_contact=mail($to,$subject,$message,$header);
// Check, if message sent to your email
// display message "We've recived your information"
if($send_contact){
echo "We've received your contact information";
}
else {
echo "ERROR";
}
?>
<? echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
Any help would be much appreciated
You probably have to modify it to look at POST:
// Details
$message=$_POST["contact_message"];
// Mail of sender
$mail_from=$_POST["contact_email"];
// From
$header="from: " . $_POST["contact_name"] . " <$mail_from>";