Sending Emails using PHP - php

I want an email to be sent to my email adress via a contact form.On the form a client will input their name,email address and a message.However when the email is sent to my address I can only see the users meessage.
How can i make it so that the clients name,email address and message is displayed in the email.
if (empty($_POST) === false) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if (empty($name) === true || empty($email) === true || empty($message) === true) {
$errors [] = 'Name ,email and message are required !';
} else {
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'That\'s not a valid email address';
}
if (ctype_alpha ($name) === false) {
$errors[] = 'Name must only contain Letters';
}
}
if (empty($errors) === true) {
mail('someone#hotmail.com', 'Contact form', $message, 'From: ' . $email);
header('Location: index.php?sent');
exit();
}
}
<!DOCTYPE html>
<html>
<head>
<title>A contact form</title>
</head>
<body>
<?php
if (isset($_GET['sent']) === true) {
echo '<p>Thanks for Contacting us !</p>';
} else {
if (empty($errors) === false) {
echo '<ul>';
foreach ($errors as $error) {
echo '<li>', $error, '</li>' ;
}
echo'</ul>';
}
?>
<form action="" method="post">
<p>
<label for="name">Name:</label><br>
<input type="text" name="name" id="name" <?php if (isset($_POST['name']) === true) {echo 'value="', strip_tags($_POST['name']), '"'; } ?>>
</p>
<p>
<label for="email">Email:</label><br>
<input type="text" name="email" id="email" <?php if (isset($_POST['email']) === true) {echo 'value="', strip_tags($_POST['email']), '"'; } ?>>
</p>
<p>
<label for="message">Message</label><br>
<textarea name="message" id="message"><?php if (isset($_POST['message']) === true) {echo strip_tags($_POST['message']); } ?></textarea>
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
<?php
}
?>
</body>
</html>

Just add the name, and email to the message. We use this method all the time with PHP mail. See the $newMessage variable below. It contains the message with the name and email added to the top of it for easy reference.
It's also easier to see what you're doing if you create a $headers variable as an array or string depending on how many additional parameters you'll have. The way I've done it here you will see the persons name in the "From" portion of the email.
<?php
if (empty($_POST) === false) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if (empty($name) === true || empty($email) === true || empty($message) === true) {
$errors [] = 'Name ,email and message are required !';
} else {
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'That\'s not a valid email address';
}
if (ctype_alpha ($name) === false) {
$errors[] = 'Name must only contain Letters';
}
}
if (empty($errors) === true) {
$headers = 'From: ' . $name . ' <' . $email . '>';
// Create the new message to send with the name and email.
$newMessage = 'Name: ' . $name . '<br/>';
$newMessage .= 'Email: ' . $email . '<br/>';
$newMessage .= $message;
mail('someone#hotmail.com', 'Contact form', $newMessage, $headers);
header('Location: index.php?sent');
exit();
}
}
?>

According to php mail() manual:
to: Receiver, or receivers of the mail.
The formatting of this string must comply with ยป RFC 2822. Some
examples are:
user#example.com
user#example.com, anotheruser#example.com
User <user#example.com>
User <user#example.com>, Another User <anotheruser#example.com>
mail() description:
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )
Example 1:
<?php
mail("john doe <nobody#example.com>", "my subject", "my message")
?>
Example 2:
<?php
$to = 'john doe <nobody#example.com>';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$message = $message. " Email: $email". " Name: $name";
You can edit the message parameter to be longer and contain more information. You can even set it to be html.
i.e. http://php.net/manual/en/function.mail.php
section 4

Related

Mail from function dispalying as unknown sender?

I am trying to display the name from the input field on a contact form to show the name that was entered after the email was submitted, I have changed headers in php and it has changed from cgi-mailer to unbknown sender? How do i get it to display the name of the person whosent the email from the contact form?
Thanks
form process php that controls validtion etc
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
$from = $_POST['name1'];
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = "From:" . $from;
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
/*if(isset($_POST['submit'])) {
$from = $_POST['name1'];
$headers = "From:" . $from;
}*/
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Conotact form html
<?php include('form_process.php');
/*if (isset($_POST['contact-submit'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "secretkeygoogle";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADOR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true) {
}else{
}
}*/
?>
<div class="home-btn"><i class="fas fa-home"></i></div>
<div class='grey'>
<div class="container-contact">
<form id="contact" method="post">
<div id="column-contact-left">
<div class='contact-logo'></div>
<h3>Contact the Devon Food Movement</h3>
<fieldset>
<input placeholder="Your name" type="text" tabindex="1" name="name1" value="<?= $name ?>" autofocus>
</fieldset>
<span class="error"><?= $name_error ?></span>
<fieldset>
<input placeholder="Your Email Address" type="text" name="email" value="<?= $email ?>" tabindex="2" >
</fieldset>
<span class="error"><?= $email_error ?></span>
</div>
<div id="column-contact-right">
<fieldset>
<textarea placeholder="Type your Message Here...." name="message" value="<?= $message ?>" tabindex="3" ></textarea>
</fieldset>
<div class="g-recaptcha" data-sitekey="needtoinput" ></div>
<span class="success"><?= $success; ?></span>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
</div>
</form>
</div>
</div>
New form p[rocess php with seperate mail function
<?php
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
/*if(isset($_POST['submit'])) {
$from = $_POST['name1'];
$headers = "From:" . $from;
}*/
}
$from = $_POST['name1'];
$headers = "From:" . $from;
if (isset($_POST['submit'])) {
mail($headers);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
LATEST PHP for the last comment i made
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$email = $_POST['email'];
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = 'From:' . $email . "\n" . 'Reply-to: ' . $email . "\n" ;
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
You must have the required fields on your form, then if you want, ask for the name too.
<?php
function defaultMailing($to, $subject, $txt, $headers){
if(mail($to, $subject, $txt, $headers)) return true; else return false;
}
?>
on the other part (where your form action):
$to = $_POST['to'];
$subject = $_POST['subject'];
$txt = $_POST['message'];
//you don't need name, but if you asked for on the form:
$msg = "thanks, ".$_POST['name']." for your message, your request will be answered soon.";
//call to mail function and send the required (to, subject and text/html message) and the optional headers if you want
defaultMailing($to, $subject, $txt, $headers);
//do whatever you want with $msg or with $_POST['name'];
If you want to insert the posted name on the message, simply modify $txt var setting the $_POST['name'] wherever you want and then, proceed with defaultMailing call, for example:
$to = $_POST['to'];
$subject = $_POST['subject'];
$txt = $_POST['message'];
$name = $_POST['name'];
$mailMessage = $name.' '.$txt;
//call to mail function and send the required (to, subject and text/html message) and the optional headers if you want
defaultMailing($to, $subject, $mailMessage, $headers);
Settles for the email being the from sender as it appears that a from value has to be a valid email address
if ($name_error == '' and $email_error == '' and ($res['success']) ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$email = $_POST['email'];
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = 'From:' . $email . "\n" . 'Reply-to: ' . $email . "\n" ;
if (mail($to, $subject, $message, $headers)) {
$sent = "Message sent";
$name = $email = $message = '';
}

Contact Form Send a copy to user/sender

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

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

Show message for empty form field?

I'm trying to get the optin form on my website to not send empty fields.
I also have predefined text within the form fields (Ex. "Enter you name here" ) that disappears on click. I don't want the form to send predefined text data either.
What is the best way to go about this with PHP?
HTML:
<div class="form">
<h2>Get An Appointment: <font size="3"><font color="#6E5769">Fill in the form below now, and I'll call you to setup your next dental appointment...</font></font></h2>
<p id="feedback"><?php echo $feedback; ?></p>
<form action="contact.php" method="post"/>
<p class="name">
<input type="text" name="name" id="name" style="text-align:center;" onClick="this.value='';" value="Enter your name"/>
PHP:
<?php
$to = 'test#mywebsite.com'; $subject = 'New Patient';
$name = $_POST['name']; $phone = $_POST['phone'];
$body = <<<EMAIL
Hi, my name is $name, and phone number is $phone.
EMAIL;
$header = 'From: test#mywebsite.com';
if($_POST){ if($name != '' && $phone != ''){ mail($to, $subject, $body, $header); }else{ $feedback = 'Fill out all the fields'; } } ?>
Collect all information in POST array and then remove the empty values using array_filter
Added an sample http://codepad.org/ZtR6Eh93
Heres try this:
<?php
$to = 'test#mywebsite.com';
$subject = 'New Patient';
$header = 'From: test#mywebsite.com';
$feedback = null;
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$name = (!empty($_POST['name'])?$_POST['name']:null);
$phone = (!empty($_POST['phone'])?$_POST['phone']:null);
$body = <<<EMAIL
Hi, my name is $name, and phone number is $phone.
EMAIL;
if($name !== null && $phone !== null){
mail($to, $subject, $body, $header);
$feedback = 'Message Sent';
}else{
$feedback = 'Fill out all the fields';
}
}
?>
For first you should do validation on client-side using JavaScript.
<?
$name = $phone = $status= '';
if(isset($_POST['submit'])){
$name = (!empty($_POST['name'])?$_POST['name']:null);
$phone = (!empty($_POST['phone'])?$_POST['phone']:null);
if($name !== null && $phone !== null){
mail($to, $subject, $body, $header);
$name = $phone = '';
$status = 'Message Sent';
}
else
$status= 'Fill out all the fields';
}
<? if(!empty($status)): ?><p class="error"><?=$status?></p><? endif; ?>
<input type="text" name="name" value="<?=$name?>"/>
<input type="text" name="phone" value="<?=$phone?>"/>
<input type="submit" name="submit" value="send"/>
I'd recommend you use empty() on the $_POST variables, preferably on the required form field (Not just $_POST). For example:
if(!empty($_POST['name'])) {
// Name field was posted
}
This is different to isset because isset will return true if the field was something like "" or NULL. Whereas !empty only accepts values that are not empty / not null. Hence why the empty function is a better choice in this case.
Hope that helps.
Add onsubmit handler to your form that set disabled property to true for all inputs which you don't like to be sent
Update:
This does not relax the requirement to check all input parameters at PHP side of your app.
You can prevent this by checking in the server side:
if($_POST){ if($name != '' && $phone != '' && $name!='Enter your name' && $email!='Enter your email'){ mail($to, $subject, $body, $header); }else{ $feedback = 'Fill out all the fields'; } } ?>
But I suggest that you improve your error handling to something like this:
if ($_POST) {
$err = array();
if ($name == '' || $name == 'Enter your name') $err[] = 'Name is required';
if ($email == '' || $email == 'Enter your email') $err[] = 'Email is required';
if (empty($err)) {
mail($to, $subject, $body, $header);
} else {
$feedback = 'Fill out all fields. Errors: '.implode(', ',$err);
}
}

HTML/PHP form not sending email

I have a form which does everything right except send the input values to my email, what am I doing wrong? Ps: not using local server, so that's not it.
EDIT: I'm not getting any email whatsoever.
Tried changing the if(isset($_POST['enviar'])) { part but still not working.
Tried the chatty echos. the only if statement that isn't behaving properly is stripslashes. It stops at the else statement.
The form snippet:
<div id="contact-wrapper">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you entered valid information.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email sent with success!</strong></p>
<p>Thank you for using our contact form <strong><?php echo $name;?></strong>, we will contact you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
</div>
<div>
<label for="email"><strong>E-mail:</strong></label>
<input type="text" size="50" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="" class="required" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
</div>
<input type="submit" value="enviar" name="submit" id="submit" />
</form>
</div>
and the PHP:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
The ereg() family of functions are deprecated. use the preg_...() equivalents instead. They work almost exactly the same, except requiring delimiters around the match patterns.
As well, don't use PHP_SELF in your form. That value is raw user-supplied data and can be trivially subverted for an XSS attack.
Checking for a particular form field to see if a POST occured is somewhat unreliable - you might change the field's name later on and your check will fail. However, this
if ($_SERVER['REQUEST_METHOD'] == 'POST) { ... }
will always work, no matter how many or few fields are in the form, as long as the form was actually POSTed.
As for the actual problem, I'm assuming the mail is getting sent out, or you'd have complained about that. That means your variables aren't being populated properly. Instead of just sending the mail, echo out the various variables as they're built, something like:
echo 'Checking name';
if ($_POST['name'] .....) {
echo 'name is blank';
} else {
$name = ...;
echo "Found name=$name";
}
Basically have your code become extremely "chatty" and tell you what it's doing at each stage.
#dafz: Change
if(isset($_POST['submit'])) {
to
if(isset($_POST['enviar'])) {
#Marc B deserves another up-vote for his answer as well.
Edit
You can try the following update.
if(!isset($hasError)) {
$siteAddress = 'validaddress#yourdomain.com'; //Put admin# or info# your domain here
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \r\nEmail: $email \r\nSubject: $subject \r\nComments: $comments \r\n";
$headers = 'To: ' . $name . ' <' . $emailTo . '>' . "\r\n";
$headers .= 'From: My Site <' . $siteAddress . '>' . "\r\n";
$headers .= 'Reply-To: ' . $email . "\r\n";
if (mail($emailTo, $subject, $body, $headers)) {
$emailSent = true;
} else {
$emailSent = false;
}
}

Categories