Sorry for the stupid question (I'm just starting out) but I can't quite understand why the phone field of my PHP script won't appear in the email I receive. I've added the field in HTML in works fine, the error message if the phone field is empty works good but if I run it, the email I receive will not contain the field.
Here is the PHP mail script:
<?php
require('email_config.php');
// sender information
$name = trim($_POST['name']);
$phone = trim($_POST['phone']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);
$error = "";
// check sender information
$pattern = "^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$^";
if(!preg_match_all($pattern, $email, $out)) {
$error = $invalid_email; // for invalid email
}
if(!$email) {
$error = $invalid_email; // for empty email field
}
if (!$phone) {
$error = $invalid_phone; // for empty phone field
}
if(!$message) {
$error = $invalid_message; // for empty message field
}
if (!$name) {
$error = $invalid_name; // for empty name field
}
// email header
$headers = "From: ".$name." <".$email.">\r\nReply-To: ".$email."";
if (!$error){
// sending email
$sent = mail($to_email,$subject,$message,$headers);
if ($sent) {
// if message sent successfully
echo "SEND";
} else {
// error message
echo $sending_error;
}
} else {
echo $error; // error message
}
?>
Thanks in advance!
Looks like you skipped adding the phone to the message, Your message
should be something like this
$message = trim($_POST['message']).' \n Phone: '.trim($_POST['phone']);
Seems like you are sending with plan text email so i used the new line special character /n.
To learn more about the special string characters
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single
Related
So I have a contact form that a user would fill out or not before submitting it. I have a PHP script that will perform the validation of what is entered instead of Javascript for greater security. I am having the PHP script encode the array into JSON format before passing it off to Javascript. I want Javascript to handle displaying the error messages accordingly and PHP only to handle the validation and sending of email (when successful).
The issue I am having is a good way to register the errors properly before passing it off to Javascript. Here is the PHP form I have so far (it has been edited to remove the printing of error messages):
<?php
ob_start();
/* Put Here email where you will receive Contact message*/
$yourEmail = "email#email.com"; // <== Your Email
$secret = 'LALALALAALALALALALALA'; // <==Your recaptcha Privte Key
/*---------------------------------------*/
// ---------------------Start the recaptcha ------------------------------------//
if(isset($_POST['g-recaptcha-response']) && ($_POST['g-recaptcha-response'])){
session_start();
$ip = $_SERVER['REMOTE_ADDR'];
$captcha = $_POST['g-recaptcha-response'];
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$captcha&remoteip=$ip");
$result = json_decode($response,TRUE);
if($result['success'] == 1){
$_SESSION['result'] = $result['success'];
}
// --------------------End Of the Captcha Check------------------------- //
/////////////Showing all errors in array : DO NOT DELETE THIS
$formerrors = array();
///////////////////This Array will Hold all errors
// Start Captcha
if(!isset($_SESSION['result']) || $_SESSION['result'] == 0){
$formerrors[] = 'Captcha Error';
}
//end Captcha
// remove this to make name not required
if(empty($_POST['name'])){
$formerrors[] = "Name Cannot be empty";
}
// End name
// Remove this to make email not required
if(empty($_POST['email'])){
$formerrors[] = "Email Cannot be empty";
}
// End of email
// Remove this to make email not required
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) == FALSE){
$formerrors[] = "Make Sure Email is valid";
}
// End of email
// Remove this to make Phone not required
if(empty($_POST['phone'])){
$formerrors[] = "Phone Number Cannot be empty";
}
// End of Phone
// Remove this to make Phone not required
if(!is_numeric($_POST['phone'])){
$formerrors[] = "Phone Is not valid";
}
// End of Phone
// Remove this to make Message not required
if(empty($_POST['message'])){
$formerrors[] = "Message Cannot be empty";
}
// End Of Message
// Remove this to make Subject not required
if(empty($_POST['subject'])){
$formerrors[] = "Select a subject First";
}
// End Of Subject
/* Your New inputs */
// CODE HERE
/* end of new Inputs*/
// End Showing Errors In Array
//JSON Encode
echo json_encode($formerrors);
if(count($formerrors) == 0){
// Saving data in variable :
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$title = $_POST['subject'];
$message = $_POST['message'];
/* Your New inputs */
// $newinput = $_POST['new-input'] // new-input same as ID and ajax
/* end of new Inputs*/
//If No Error in the Array Start Sending the email
$to = $yourEmail; // Email to receive contacts
$from = $email;
$subject = 'Contact Form Email : ' . $title;
$message = '<style>
body{background-color:#fefefe}
.email-style {padding: 30px;background: #fafafa;font-size: 18px;border: 1px solid #ddd;width: 60%;margin: auto;}
p {padding: 15px 0px;}
</style>
<div class="email-style"><p> '.$title . '</p>
<p>Contact Full Name : '.$name . ' </p>
<p>Contact Email : '.$email . ' </p>
<p>Contact Phone Number : '.$phone . '</p>
<p>Message : '.$message . ' </p>
<p>Cheers,</p>
<p>'.$name.' Via Contact Form</p></div>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
if( mail($to, $subject, $message, $headers) ){
echo "sent";
session_unset();
session_destroy();
} else {
echo "The server failed to send the message. Please try again later.";
}
}
}
ob_flush();
?>
Can anyone please suggest a method of registering the error messages properly and cleanly?
I have a Contact Form which submits the data using AJAX to a PHP mailer. Once the email have been sent a confirmation message is shown to the user. It works well. My problem is how to customize the confirmation message based on which fields have been filled.
The form has four fields. Name (required), Subject (option list: by default 'Subscribe to Newsletter'), Email (required) and Message and there are two cases:
1) User is only looking to get subscribed to the Newsletter. Only 'Name' and 'Email' fields are filled. Confirmation message A.
2) User sends an email. 'Name', 'Email' and 'Message' are filled. Confirmation message B.
This is my current code, shows a general confirmation message:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = strip_tags(trim($_POST["name"]));
$asunto = strip_tags(trim($_POST["asunto"]));
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "¡Error 400 bla bla...!
exit;
}
$recipient = "name#domain.com";
$subject = "Nauta $name";
$email_content = "Nombre: $name\n";
$email_content = "Asunto: $asunto\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Mensaje:\n$message\n";
$email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "¡Thank you! bla bla...";
}
else {
http_response_code(500);
echo "¡Error 500 bla bla...!
}
}
else {
http_response_code(403);
echo "¡Error 403 bla bla...!
}
I tried the following structure (elseif) with no luck.
if ( ) {
echo "...";
} elseif ( ) {
echo "...";
} else {
echo "...";
}
No results.
Try to ask if message is an empty string or one blank character:
if ($_POST['message']!="") {
...
}
Thank you, #Carmen. It didn't work but I have found the way to make it work.
if (empty($_POST['message'])) {
...
}
I'm trying to create a contact form where the user will fill out their name, email, subject and message in order to contact me. It is suppose to send an email to my email account but every time i test it, it does not work. I was positive it was correct, but i guess it is not. Any help please?
<?php
//Get user input
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"]
$message = $_POST["message"];
//error messages
$missingName = '<p><strong>Please enter your name!</strong></p>';
$missingEmail = '<p><strong>Please enter your email address!</strong></p>';
$invalidEmail = '<p><strong>Please enter a valid email address!</strong></p>';
$missingSubject = '<p><strong>Please enter a Subject!</strong></p>';
$missingMessage = '<p><strong>Please enter a message!</strong></p>';
//if the user has submitted the form
if($_POST["submit"]){
//check for errors
if(!$name){
$errors .= $missingName;
}else{
$name = filter_var($name,FILTER_SANITIZE_STRING);
}
if(!$email){
$errors .= $missingEmail;
}else{
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
$errors .=$invalidEmail;
}
}
if(!$subject){
$errors .= $missingSubject;
}else{
$message = filter_var($subject, FILTER_SANITIZE_STRING);
}
if(!$message){
$errors .= $missingMessage;
}else{
$message = filter_var($message, FILTER_SANITIZE_STRING);
}
//if there are any errors
if($errors){
//print error message
$resultMessage = '<div class="alert alert-danger">' . $errors .'</div>';
}else{
$to = "fanonxr#gmail.com";
$subject = "Contact";
$message = "
<p>Name: $name.</p>
<p>Email: $email.</p>
<p>Subject: $subject.</p>
<p>Message:</p>
<p><strong>$message</strong></p>";
$headers = "Content-type: text/html";
if(mail($to, $subject, $message, $headers)){
$resultMessage = '<div class="alert alert-success">Thanks for your message. We will get back to you as soon as possible!</div>';
header("Location: index.php");
}else{
$resultMessage = '<div class="alert alert-warning">Unable to send Email. Please try again later!</div>';
}
}
echo $resultMessage;
}
?>
it seems you are missing the form action and mailto since its Html i think those should be included.
your validation looks good to me.
In terms of sending email, try finding some answers here:
PHP mail form doesn't complete sending e-mail
If that doesn't address your question, please provide some more info, like what mailer you're using. Hope this helps :)
I've found a template that I want to edit and it already has a nice looking contact form. After hitting the submit button I'm getting a thank you message but I would like to redirect to another page where the message will appear so I can use it for conversion tracking.
Could someone be of assistance what should I do as my current code looks like this:
<?php
$firstname = '';
$number = '';
$message = '';
$email = '';
if($_POST) {
// collect all input and trim to remove leading and trailing whitespaces
$firstname = trim($_POST['first_name']);
$number = trim($_POST['phone']);
$message = trim($_POST['message']);
$email = trim($_POST['email']);
$errors = array();
// Validate the input
if (strlen($firstname) == 0)
array_push($errors, "Please enter your name");
if (strlen($number) == 0)
array_push($errors, "Please specify your number");
if (strlen($message) == 0)
array_push($errors, "Please enter the details of your message");
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
array_push($errors, "Please specify a valid email address");
// If no errors were found, proceed with storing the user input
if (count($errors) == 0) {
//completion message into array
$to = 'me#mymailzz.com'; // note the comma
// the email subject ( modify it as you wish )
$subject = "Enquiry From website";
// the mail message ( add any additional information if you want )
$msg = "Quote From website:\n-------------------------------------------\n Name: $firstname \n Number: $number \n Email: $email \n Message: $message \n-------------------------------------------";
//function to send email
try {
mail($to, $subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
$return1 = "Thank You for sending your message, we will be in touch within 48-72 hours";
array_push($errors, $return1);
$formsubmit = 1;
}catch(Exception $e){
$return3 = "<center><p><b>Your message did not get sent due to an error. Please try again. Caught Exception {$e->getMessage()}</center>";
array_push($errors, $return3);
$formsubmit = 0;
}
}
//Prepare errors for output
$output = '';
foreach($errors as $val) {
$output .= "<p class='output'>$val</p>";
}
}
?>
Replace the line:
$return1 = "Thank You for sending your message, we will be in touch within 48-72 hours";
With something like this:
header('Location: some_page.php');
exit;
And then you can remove these lines as they become obsolete:
array_push($errors, $return1);
$formsubmit = 1;
That will redirect to some_page.php instead of printing that message.
To store the message across pages, do this at the start of your script:
session_start();
Instead of storing messages in a normal variable, store it in a session variable, e.g.:
$_SESSION['message'] = 'Your message here';
At the end of your script:
if ($formsubmit == 1) {
header('Location: your-file.php');
}
In your-file.php:
<?php
session_start();
echo $_SESSION['message'];
Just made a change in your try code and insert redirect fuunction
try {
mail($to, $subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.location.href='next_page.php'
</SCRIPT>");
}
How about you trace in your web template where you have <form action="#"> and proceed with help from a previously similar asked question found here
The following code sends me an email holding the following variables. One of the last if statements says if(mail) then echo "You will be contacted soon". When the script runs I get echoed back "You will be contacted soon", however, I never receive an email.
I do have a smaller contact script (posted after this first and larger one) that does work.
Note: contants.php and functions.php are both included and work fine
WEBMASTER_EMAIL is defined in contanstants.php and is correct, because
my smaller contact script uses the same variable, and emails me fine.
Thanks for the help
<?php
// pull constant variables
include("php/constants.php");
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post) {
include ("php/functions.php");
}
// general info
$name = stripslashes($_POST['contact']);
$phone = $_POST['phone'];
$email = trim($_POST['email']);
$time_to_reach = $_POST['time-to-reach']; // what the best time to reach them?
// delivery info
$delivery_address = $_POST['del-address'];
$delivery_city = $_POST['del-city'];
$delivery_state = $_POST['del-state'];
$delivery_zip = $_POST['del-zip'];
// moving city info if applicable
$moving_address = $_POST['move-address'];
$moving_city = $_POST['move-city'];
$moving_state = $_POST['move-state'];
$moving_zip = $_POST['move-zip'];
// date needed
$month = $_POST['month'];
$day = $_POST['day'];
$year = $_POST['year'];
// how long do you need the storage?
$storage_length = $_POST['time-length'];
// how many containers do you need?
$quantity_containers = $_POST['number-of-containers'];
// how did you hear about us?
$tracker = $_POST['tracker'];
// message
$message_holder = htmlspecialchars($_POST['message']);
$error = '';
// check general info
if(!$name) { $error .= 'Please enter your name.<br />'; }
if(!$email) { $error .= 'Please enter an e-mail address.<br />'; }
if($email && !ValidateEmail($email)) { $error .= 'Please enter a valid e-mail address.<br />'; }
if(!$time_to_reach) { $error .= 'Please select the best time to reach you.<br />'; }
// check delivery info
if(!$delivery_address) { $error .= 'Please enter you current address.<br />'; }
if(!$delivery_city) { $error .= 'Please enter your current city.<br />'; }
if(!$delivery_state) { $error .= 'Please enter your current state.<br />'; }
if(!$delivery_zip) { $error .= 'Please enter your current zip code.<br />'; }
// check date needed
if(!$month) { $error .= 'Please enter the approximate date you need the storage.<br />'; }
if(!$day) { $error .= 'Please enter the approximate date you need the storage.<br />'; }
if(!$year) { $error .= 'Please enter the approximate date you need the storage.<br />'; }
// check length of time needed
if(!$storage_length) { $error .= 'Approximatly how long will you need the storage unit for?<br />'; }
// check quantity of storages
if(!$quantity_containers) { $error .= 'How many containers will you need?<br />'; }
// check advertising tracker
if(!$tracker) { $error .= 'Please let us know how you\'ve heard of us.<br />'; }
// check message (length)
if(!$message_holder || strlen($message_holder) < 10) {
$error .= "Please enter your message. It should have at least 10 characters.<br />";
}
// build email message
$message = "Name: {$name}
Phone: {$phone}
Email: {$email}
Best time to reach: {$time_to_reach}\n
-----------------------------------------------------
Delivery address: {$delivery_address}
{$delivery_city}, {$delivery_state} {$delivery_zip}
Moving address: {$moving_address}
{$moving_city}, {$moving_state} {$moving_zip}
-----------------------------------------------------
Date needed: {$month}/{$day}/{$year}
Length of time needed: {$storage_length}
Number of containers: {$quantity_containers}
Where did you hear about us?
{$tracker}\n
Message: {$message_holder}\n";
if(!$error) {
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: residential-quote#stocor.com\r\n"
."Reply-To: ".$name."<".$email.">\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail) {
echo '<p>Thank you, you will be contacted soon.</p>';
}
} else {
echo '<div class="notification_error">'.$error.'</div>';
}
?>
The following script, contact script, does work meaning I receive an email.
<?php
// pull constant variables
include("php/constants.php");
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post) {
include ("php/functions.php");
}
// variables
$name = stripslashes($_POST['name']);
$phone = $_POST['phone'];
$email = trim($_POST['email']);
$tracker = $_POST['tracker'];
$message_holder = htmlspecialchars($_POST['message']);
$error = '';
// check name
if(!$name) {
$error .= 'Please enter your name.<br />';
}
// check email
if(!$email) {
$error .= 'Please enter an e-mail address.<br />';
}
// validate email
if($email && !ValidateEmail($email)) {
$error .= 'Please enter a valid e-mail address.<br />';
}
// check advertising tracker
if(!$tracker) {
$error .= 'Please let us know how you\'ve heard of us.';
}
// check message (length)
if(!$message_holder || strlen($message_holder) < 10) {
$error .= "Please enter your message. It should have at least 10 characters.<br />";
}
// build email message
$message = "Name: {$name} \n
Phone: {$phone} \n
Email: {$email} \n
Where did you hear about us?
{$tracker}\n\n
Message: {$message_holder}\n";
if(!$error) {
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: contact#stocor.com\r\n"
."Reply-To: ".$name."<".$email.">\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail) {
//header("Location: thank_you.php");
echo "Thank you. You will be contacted soon.";
}
} else {
echo '<div class="notification_error">'.$error.'</div>';
}
?>
Using the naked mail function is just asking for trouble ( http://en.wikipedia.org/wiki/E-mail_injection , php specific info: http://www.damonkohler.com/2008/12/email-injection.html ), and prevents simple debugging. I suggest you use an object wrapper around the mail function, both because this has benefits when you filter the headers, by making it a non-standard target for php mail form header injection spammers, and by allowing you to debug the messages easier by just dumping the created mail object and reviewing it's contents. For debugging it also allows you to provide a "just echo out the mail at the end" alternative for local testing on machines where you don't have/don't want to have a mail server, and don't want to even try to send out mail while you're just testing functionality.
Here is a wrapper (freely available for modification and use) that I created and use myself:
http://github.com/tchalvak/ninjawars/blob/master/deploy/lib/obj/Nmail.class.php
Alternatively just check out PEAR mail: http://pear.php.net/package/Mail/
It's not jumping out at me, why don't you try turning the errors all the way up and see if that works.
error_reporting(1);
At the top of the script.
EDIT: Sorry, I see now you do have error reporting turned on. Make sure your INI file is set properly too. Try removing the ^ E_NOTICE so that you see those warnings, too.
I've had problems where mail() wouldn't say anything at all (and it would execute as if successful) when it didn't really. If you're bent on using mail(), you can use SwiftMailer, which generally throws helpful exceptions when something goes awry and includes a transport class Swift_MailTransport which uses mail() but is all dressed up in a nice object-oriented interface.
So, due to the nature of the problem (mail is being accepted for delivery - $mail is true), the problem is likely in the message content. Do you have access to the mail server itself? Can you check the logs? var_dump() the $subject, $message, and set the headers to a var and var_dump() that as well. Examine the contents with a fine tooth comb. Remove suspect characters and line breaks until it does work.
One thing to try... (though, the fact that your other mail is being accepted says this is likely not the case)
http://www.php.net/manual/en/function.mail.php
If messages are not received, try
using a LF (\n) only. Some poor
quality Unix mail transfer agents
replace LF by CRLF automatically
(which leads to doubling CR if CRLF is
used). This should be a last resort,
as it does not comply with » RFC 2822.
The problem with mail() is that its just feeding mail to the local sendmail daemon. It doesn't give you any active feedback on the mail, and the relay headers sometimes get you spam de-rated.
I'd check out http://sourceforge.net/projects/phpmailer/
Try wrapping lines in the message to 70 characters with
$message = wordwrap($message, 70);
Try replacing \r\n in the additional headers with \n in case your mail function is replacing \n for \r\n and you're ending-up with \r\r\n