Contact Form Send a copy to user/sender - php

I have a website template with a contact form and sendmail.php file. What I want to do is give the sender the option to send a copy of the form to themselves.
I've tried different suggestions which I've found online but without success.
I've managed to get the checkbox option in the html file pretty easily, but even if it's selected, the sender doesn't get a copy of the email. So my thinking is that there's something on the PHP end that I'm missing or have down incorrectly.
I tried:
//cc option
$headers["From"] = "$clientEmail";
$headers["To"] = "$emailTo";
$headers["Subject"] = $subject;
$headers['Cc'] = '$clientEmail';
but that didn't work.
Here is the HTML and PHP code:
HTML:
<div class="contact-us container">
<div class="row">
<div class="contact-form span7">
<p>Want to get in touch? Use the form below to send an email.</p>
<form method="post" action="assets/sendmail.php">
<label for="name" class="nameLabel">Name</label>
<input id="name" type="text" name="name" placeholder="Enter your name...">
<label for="email" class="emailLabel">Email</label>
<input id="email" type="text" name="email" placeholder="Enter your email...">
<label for="subject">Subject</label>
<input id="subject" type="text" name="subject" placeholder="Your subject...">
<label for="message" class="messageLabel">Message</label>
<textarea id="message" name="message" placeholder="Your message..."></textarea>
<button id="button">Send</button>
</form>
<input type="checkbox" value="1" id="sendCopy" name="sendCopy" class="rsp-cB"/>
<label for="sendCopy">Send me a copy.</label>
</div>
</div>
</div>
PHP:
// Email address verification
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'email#gmail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your name.';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName != '' && isEmail($clientEmail) && $message != '') {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject, $message, $headers);
}
header('Location: thanks.php');
}?>
I'm a complete newbie so please suggest, in layperson terms, what is required and in which files and where.
P.S. I know there are other similar questions on here, but I've tried them as well as googling for other suggestions and I haven't been able to get it to work.

You cant use headers as array like this
// Cc option
$headers["From"] = "$clientEmail";
$headers["To"] = "$emailTo";
$headers["Subject"] = $subject;
$headers['Cc'] = "$clientEmail";
Correct way is.
$to = 'reciver_address#gmail.com'; // Recipient of email
$subject = 'I\'m sending a mail'; // Subject of email
$message = 'This is message'; // Body of email
$header = 'From: address#gmail.com'; // Sender email address
$header .= "\r\n" . 'Cc: copy#gmail.com'; // Copy of email
Then in mail()
mail($to, $subject, $message, $header);

Try this header.
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n";
$headers .= "Reply-To: " . $clientEmail. "\r\n";
$headers .= "Cc: " . $clientEmail. "\r\n";

You are right, there is the PHP Part missing. If you use the BuildIN PHP Mail function you have to add the CC to the headers.
Not tested, but add this to your code below the first "$header" and it should send an copy to the Client:
// add CC when checked in Form and attach to headers
if ($_POST['sendCopy'] == '1') {
$headers .= "Cc: $clientEmail" . "\r\n";
}
I would recommend to have a look at some better Mail Solutions like: PHPMailer

please try this(ignore code before)
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
if($_POST['sendCopy']=="1") {
// Enter the email where you want to receive the message
$emailTo = 'email#gmail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your name.';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName != '' && isEmail($clientEmail) && $message != '') {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject, $message, $headers);
}
header('Location: thanks.php');
}
}
?>

Related

'phone' is not displayed in the mail form

The mail is sent successfully to my domain-mail. however, the 'phone' is not sent in the mail content.
The content of the mail comes like this.
You have been contacted by yourname with regards, their additional message
is as follows.
"What I want to say~~ "
You can contact yourname via email, omain#domain or via phone
What's the problem?
<form method="post" action="php/contact.php" name="contactform" id="contactform">
<input name="name" type="text" id="name" onClick="this.select()" value="Name" >
<input name="email" type="text" id="email" onClick="this.select()" value="E-mail" >
<input type="text" name="phone" id="phone" onClick="this.select()" value="Phone" />
<textarea name="comments" id="comments" onClick="this.select()" >Message</textarea>
<button type="submit" id="submit" data-top-bottom="transform: translateY(-50px);" data-bottom-top="transform: translateY(50px);"><span>Send Message </span></button>
</form>
<?php
require 'PHPMailer-master/PHPMailerAutoload.php';
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$fromEmail = $_REQUEST['email'] ;
$fromName = $_REQUEST['name'] ;
$to_Email = "my#domain.com";
// Email address verification, do not edit.
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">You must enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message"> Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Phone number can only contain digits.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">You have enter an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Please enter your message.</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 = "my#domain.com";
$address = "my#domain.com";
// 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 = 'You\'ve been contacted by ' . $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 = "You have been contacted by $name with regards, their additional message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email or via phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$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>Email Sent Successfully.</h3>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
It seems to me that this needs to be corrected...
$e_reply =
<input type="text" name="phone" id="phone" onClick="this.select()" value="Phone" />
by removing "/" at the end of the tag may help you.

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 email - want to send to different emails

Currently:
I have the PHP form below, where users select one of the checkboxes a notification comes as to which location they are looking to book.
Goal:
I would like it to now be that when someone clicks Canterbury an email is sent to email1#gmail.com, when to Broadstairs - email2#gmail.com, and when to deal - email3#gmail.com
I have been going in circles trying to make the changes but I get in a mess.
FYI I don't mind changing the checkboxes into a dropdown, but I would rather keep it this way.
Current PHP section:
<?php
ini_set('display_errors',0);
error_reporting(E_ALL);
$error = '';
if(isset($_POST['send']))
{
$name = $_REQUEST['Name'];
$telephone = $_REQUEST['Telephone'];
$email = $_REQUEST['Email'];
$message = $_REQUEST['Message'];
$headers = "From: $email";
$subject = "Web Contact Data";
$selectedProjects = 'None';
if(isset($_POST['projects']) && is_array($_POST['projects']) && count($_POST['projects']) > 0){
$selectedProjects = implode(', ', $_POST['projects']);
}
$fields = array();
$fields["Name"] = $name;
$fields["Telephone"] = $telephone;
$fields["Email"] = $email;
$fields["Message"] = $message;
$fields["Location"] = $selectedProjects;
$to = "email4#gmail.com" ; // change all the following to $_POST
$body = "You have recieved the following information:\n\n";
foreach($fields as $key => $value)
{
$body .= sprintf("%20s: %s\n",$key,$value);
} // end foreach($fields as $key => $value)
$subject2 = "Thank you for contacting us.";
$autoreply = "<html><body><p>Dear " . $name . ",</p><p>Message goes here.</p></body></html>";
$headers2 = 'MIME-Version: 1.0' . "\r\n";
$headers2 .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers2 .= 'From: email4#gmail.com' . "\r\n";
$send=false;
if($name == '')
{
$error = "You did not enter your name, please try again.";
selected_values();
}
$send=false;
if($telephone == '')
{
$error = "You did not enter your telephone number, please try again.";
selected_values();
}
elseif(!preg_match("/^[[:alnum:]][a-z0-9_.'+-]*#[a-z0-9-]+(\.[a-z0-9-]{2,})+$/", $email))
{
$error = "You did not enter a valid email address, please try again.";
selected_values();
}
else
{
$send = mail($to, $subject, $body, $headers);
$send2 = mail($email, $subject2, $autoreply, $headers2);
if(!isset($error) && !$send)
{
$error = "We have encountered an error sending your mail, please notify [email]email4#gmail.com[/email].";
}
else
{
unset($_REQUEST['Name']);
unset($_REQUEST['Email']);
unset($_REQUEST['Telephone']);
unset($_REQUEST['Message']);
}
} // end else
}// end of if(isset($_POST['send']))
?>
And the HTML form is this:
<form method="post" action="./lead.php">
<ul>
<li>
<?php
if(isset($error))
echo '<div class="register_error">'.$error.'</div>';
if(isset($send) && $send== true){
=echo '<div class="contact-send-green">Thank you for your message.</div>';
}
if(!isset($_POST['send']) || isset($error))
?>
</li>
<li>
<input type="checkbox" name="projects[]" value="Broadstairs">
<label for="type2">Broadstairs</label>
<br /><br />
<input type="checkbox" name="projects[]" value="Canterbury">
<label for="type2">Canterbury</label>
<br /><br />
<input type="checkbox" name="projects[]" value="Deal">
<label for="type2">Deal</label>
</li>
<li>
<textarea name="Message" rows="5" cols="29"><?php if(isset($_REQUEST['Message'])) echo $_REQUEST['Message']; ?></textarea>
</li>
<li>
<input type="submit" name="send" value="Send Message" id="send-email">
</li>
</ul>
For single selection a simple switch(){} would do the magic.
switch($_POST['projects']){
case "Broadstairs":
$to = "email#email.com";
break;
case "Canterbury":
$to = "email#email.com";
break;
case "Deal":
$to = "email#email.com";
break;
}
And then remove the [] from the input names as you won't need them to be a array. (As such:)
<input type="checkbox" name="projects" value="Broadstairs">
And then perhaps considering using some JS/jQuery to check that only 1 is selected at a time?
There are 3 issues with the script you have provided
You want to select only a single email address however, you are using the name projects[] as the checkbox names - this will create an array, however since HTML5; if you use a name multiple times even without the [] it will create an array.
Given the above, you should most definitely as you mentioned change to a <select> box, or alternatively <radio> buttons.
You should not use $_REQUEST unless absolutely needed, you are providing an easy oppurtunity for sql injection.
Here is an example of how I would do it.
HTML
<form method="post" action="./lead.php">
<ul>
<li>
<?php
if(isset($error)) echo '<div class="register_error">'.$error.'</div>';
if(isset($send) && $send== true) echo '<div class="contact-send-green">Thank you for your message.</div>';
?>
</li>
<li>
<label for="Broadstairs"><input type="radio" name="projects" id='Broadstairs' value="Broadstairs"> Broadstairs</label>
<label for="Canterbury"><input type="radio" name="projects" id='Canterbury' value="Canterbury">Canterbury</label>
<label for="Deal"><input type="radio" name="projects" id='Deal' value="Deal">Deal</label>
</li>
<li>
<textarea name="Message" rows="5" cols="29"><?=(strlen($_POST['Message'])>0) ? $_POST['Message'] : ''; ?></textarea>
</li>
<li>
<button type='submit'>Send Message</button>
</li>
</ul>
And your PHP
<?php
if (!empty($_POST)) {
// Dispatch message to selected office
$name = $_POST['Name'];
$telephone = $_POST['Telephone'];
$email = $_POST['Email'];
$message = $_POST['Message'];
$subject = "Web Contact Data";
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: My website <my-email#example.com>' . "\r\n";
if ($_POST['projects'] == 'Canterbury') $to = "example#gmail.com" ;
elseif ($_POST['projects'] == 'Broadstairs') $to = "example#gmail.com" ;
else $to = "example#gmail.com" ;
mail($to, $subject, $message, $headers);
// Dispatch "Thank You" email
$subject = "Your message has been received!";
ob_start();
?>
<html>
<body>
<p>Dear <?=$name?></p>
<p>Thank you for contacting us,</p>
<p>We have received your message and will respond to you as soon as possible.</p>
<p>This is an automatic response to your inquiry and it is not necessary to reply.</p>
<p>Thank you,</p>
</body>
</html>
<?
$message = ob_get_flush();
mail($email, $subject, $message, $headers)
}
?>
I would recommend Google Recaptcha too.
Hope this helps
You need to add if, elseif, and else condition to your code.
Replace $to = "email1#email.com" ; with following code
if($_POST['projects'] == 'Broadstairs')
{
$to = "email2#email.com";
}
else if($_POST['projects'] == 'Canterbury')
{
$to = "email3#email.com";
}
else if($_POST['projects'] == 'Deal')
{
$to = "email4#email.com";
}
else
{
$to = "email5#email.com";
}

sendmail.php not re-directing

I had/have the code below for users to send messages/emails from my website to my sites email address.
It was working fine, for weeks: Validating the field contents (if there was a blank 'required field', it asked for a "valid" field content i.e. email address), as long as there were no blank fields it was sending the email and was re-directing to the thank-you page - which acknowledges that the email has been sent.
Now, it has stopped working properly.
It doesn't seem to be validating (as it did originally) any more - as there are no warnings/errors for blank fields (if there is a blank field it simply doesn't send), it still sends the email to the address correctly (if there are no blank required fields), but it doesn't redirect to the thank-you page any more.
Here is the form code:
<form method="post" action="assets/sendmail.php">
<label for="name" class="nameLabel">Name</label>
<input id="name" type="text" name="name" placeholder="Enter your name...">
<label for="email" class="emailLabel">Email</label>
<input id="email" type="text" name="email" placeholder="Enter your email...">
<label for="subject">Subject</label>
<input id="subject" type="text" name="subject" placeholder="Your subject...">
<label for="message" class="messageLabel">Message</label>
<textarea id="message" name="message" placeholder="Your message..."></textarea>
<button type="submit">Send</button>
</form>
Here is the php code - note that I have substituted the email address for obvious reasons :)
<?php
// Email address verification
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|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($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'me#myemail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your name.';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName != '' && isEmail($clientEmail) && $message != '') {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject, $message, $headers);
}
//echo json_encode($array);
{
header("location:../thankyou.html");
}
}
?>
Any help would be appreciated.
First of all, for email checking you can use built-in php as well.
filter_var($clientEmail, FILTER_VALIDATE_EMAIL)
I don't see where you output your errors so that may be why they are not showing,
I have added support for that
I have rewritten your code:
<?php
if (!empty($_POST)) {
// Enter the email where you want to receive the message
$emailTo = 'me#myemail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$errors = array();
if (empty($clientName)) {
$errors['nameMessage'] = 'Please enter your name.';
}
if (!filter_var($clientEmail, FILTER_VALIDATE_EMAIL)) {
$errors['emailMessage'] = 'Please insert a valid email address.';
}
if (empty($message)) {
$errors['messageMessage'] = 'Please enter your message.';
}
// Are there errors?
if (count($errors) == 0) {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject, $message, $headers);
header("location:../thankyou.html");
} else {
foreach ($errors as $err) {
echo $err . '<br />';
}
}
}
?>
Thank-you for the updated PHP code. Unfortunately, it hasn't made any difference. It still sends the email when all fields are filled in, it even sends if the "subject" is empty, but it still does not re-direct to the thank-you page. It doesn't send if Name, Email Address, and Message are empty. But it does not display errors. I have tried to place both files in the parent directory and removing the assets/ from the action in the form and the ../ in the PHP. as below
<form method="post" action="sendmail.php">
<label for="name" class="nameLabel">Name</label>
<input id="name" type="text" name="name" placeholder="Enter your name...">
<label for="email" class="emailLabel">Email</label>
<input id="email" type="text" name="email" placeholder="Enter your email...">
<label for="subject">Subject</label>
<input id="subject" type="text" name="subject" placeholder="Your subject...">
<label for="message" class="messageLabel">Message</label>
<textarea id="message" name="message" placeholder="Your message..."></textarea>
<button type="submit">Send</button>
</form>
And the PHP is as you supplied (changing the email address of course)
<?php
if (!empty($_POST)) {
// Enter the email where you want to receive the message
$emailTo = 'me#myemail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$errors = array();
if (empty($clientName)) {
$errors['nameMessage'] = 'Please enter your name.';
}
if (!filter_var($clientEmail, FILTER_VALIDATE_EMAIL)) {
$errors['emailMessage'] = 'Please insert a valid email address.';
}
if (empty($message)) {
$errors['messageMessage'] = 'Please enter your message.';
}
// Are there errors?
if (count($errors) == 0) {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject, $message, $headers);
header("location:thankyou.html");
} else {
foreach ($errors as $err) {
echo $err . '<br />';
}
}
}
?>
No Errors displayed if there are errors, no re-direct once sent. It just remains on the "contact" page and still displaying the completed form. Cannot understand why the re-direct was working but not now. Couldn't sign in when I posted this originally.

PHP contact form script not sending emails

I am not very good with php and my friend helped me with this php contact form script. But this does not seem to send emails to the desired address. Can you please suggest what might be the problem with this script?
I really appreciate it. Thanks
<?php
$error = array();
if(!empty($_POST['contact_submit']) && ($_POST['contact_submit'] == 'submit') ) {
if(!empty($_POST['name'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your name.';
}
if(!empty($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
} else {
$error[] = 'Please enter a correct email address.';
}
} else {
$error[] = 'Please enter your email address.';
}
if(!empty($_POST['phone'])) {
if(filter_var($_POST['phone'], FILTER_VALIDATE_INT)) {
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
} else {
$error[] = '<i>Phone number</i> only expects number';
}
} else {
$error[] = 'Please enter your email address.';
}
if(!empty($_POST['time'])) {
$time = filter_var($_POST['time'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your best time to contact.';
}
if(!empty($_POST['msg'])) {
$msg = filter_var($_POST['msg'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your message.';
}
if(empty($error)) {
$to = 'your#email.com';
$subject = 'from contact form';
$message = $phone . "\r\n";
$message .= $time . "\r\n";
$message .= $msg;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$name.' <'. $email.'>' . "\r\n" .
'Reply-To: '.$name.' <'. $email . '>' ."\r\n";
//echo '<pre>'; var_dump($to, $subject, $message, $headers); echo '</pre>'; die();
mail($to, $subject, $message, $headers);
}
}
?>
<?php
if(!empty($error)) {
echo '<ul class="error">';
echo '<li>' . implode('</li><li>', $error) . '</li>';
echo '</ul>';
}
?>
<form method="post" action="">
<input type="text" name="name" value="" placeholder="Enter your name" class="email_form"/>
<input type="text" name="email" value="" placeholder="Enter your email address" class="email_form"/>
<input type="text" name="phone" value="" placeholder="Phone number" class="email_form"/>
<input type="text" name="time" value="" placeholder="Best time to contact. e.g. 3 am" class="email_form"/>
<textarea name="msg" placeholder="Your message" class="email_form"></textarea>
<input type="image" value="submit" name="contact_submit" src="images/submit.png" width="96" height="43" class="email_button">
</form>
Change this line:
if(!empty($_POST['contact_submit']) && ($_POST['contact_submit'] == 'submit') ) {
to
if(isset($_POST['contact_submit']) ) {
and
<input type="image" value="submit" name="contact_submit" src="images/submit.png" width="96" height="43" class="email_button">
to
<input type = "submit" value="submit" name="contact_submit">
PHP is looking for a submit type, and you're using an image type.
If you still want to use the image as the submit button:
You will need to change:
if(!empty($_POST['contact_submit']) && ($_POST['contact_submit'] == 'submit') )
to another conditional statement.
For example:
if(!empty($_POST['email'])){
You can always add on to that conditional statement with the other fields you wish to check if they are set/empty.
For example:
if(!empty($_POST['email']) || !empty($_POST['name'])){
Upon testing your code, the code did not work till those changes were made.
N.B.: If mail is still not being sent/received, you will need to make sure that mail() is indeed available for you to use, and/or check your logs and the Spam box.
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
Which will trigger any errors found.
Footnotes:
The phone field needs to be all numbers, otherwise it will fail.
I.e.: 555-234-5678 did not work, but 5552345678 did, therefore you will need to inform your users of how it should be entered.
Edit: (full code) - copy exactly as shown while changing email#example.com to your own Email.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$error = array();
if(isset($_POST['contact_submit']) ) {
if(!empty($_POST['name'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your name.';
}
if(!empty($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
} else {
$error[] = 'Please enter a correct email address.';
}
} else {
$error[] = 'Please enter your email address.';
}
if(!empty($_POST['phone'])) {
if(filter_var($_POST['phone'], FILTER_VALIDATE_INT)) {
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
} else {
$error[] = '<i>Phone number</i> only expects number';
}
} else {
$error[] = 'Please enter your email address.';
}
if(!empty($_POST['time'])) {
$time = filter_var($_POST['time'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your best time to contact.';
}
if(!empty($_POST['msg'])) {
$msg = filter_var($_POST['msg'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your message.';
}
if(empty($error)) {
$to = 'email#example.com';
$subject = 'from contact form';
$message = $phone . "\r\n";
$message .= $time . "\r\n";
$message .= $msg;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$name.' <'. $email.'>' . "\r\n" .
'Reply-To: '.$name.' <'. $email . '>' ."\r\n";
//echo '<pre>'; var_dump($to, $subject, $message, $headers); echo '</pre>'; die();
mail($to, $subject, $message, $headers);
}
}
?>
<?php
if(!empty($error)) {
echo '<ul class="error">';
echo '<li>' . implode('</li><li>', $error) . '</li>';
echo '</ul>';
}
?>
<form method="post" action="">
<input type="text" name="name" value="" placeholder="Enter your name" class="email_form"/>
<input type="text" name="email" value="" placeholder="Enter your email address" class="email_form"/>
<input type="text" name="phone" value="" placeholder="Phone number" class="email_form"/>
<input type="text" name="time" value="" placeholder="Best time to contact. e.g. 3 am" class="email_form"/>
<textarea name="msg" placeholder="Your message" class="email_form"></textarea>
<input type = "submit" value="submit" name="contact_submit">
</form>
You can also show a message if it was sent successfully by replacing:
mail($to, $subject, $message, $headers);
with:
if(mail($to, $subject, $message, $headers)){
echo "Mail sent, thank you.";
}
else{
echo "There was an error.";
}
You can also log the error:
http://php.net/manual/en/function.error-log.php
0 message is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. This is the default option.
1 message is sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used.
2 No longer an option.
3 message is appended to the file destination. A newline is not automatically added to the end of the message string.
4 message is sent directly to the SAPI logging handler.
I.e.:
if(mail($to, $subject, $message, $headers)){
echo "Mail sent, thank you.";
}
else{
error_log("Error!", 3, "/var/tmp/mail-errors.log");
}

Categories