I have a simple website with a php contact form set up.
The original contact form included:
$to = "my_email#gmail.com";
$subject = "New message: $name";
$message = "$message";
$headers = "From: $email";
mail($to, $subject, $message, $headers);
but, it never actually sent an emial. My hosting provider claimed they cannot allow such a thing since the way it is, email spoofing can be done. Fine. So, after reading a thread here (php Contact Form on website and reply-to email) I modified the part above to the following:
$to = "my_email#gmail.com";
$subject = "New message: $name";
$message = "$message";
$headers = "From: my_email#gmail.com" . "\r\n" .
"Reply-To: $email" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
mail($to, $subject, $message, $headers);
which worked fine.
Now, I pretty much just uploaded the same site (some design and textual changes, nothing big) under a new domain on the same host (even the same shared hosting server), but it doesn't work. The contact form confirms sending but emails do not arrive.
Any ideas?
Your help would be greatly appreciated :)
Update: for what it's worth, here's the full php file:
<?php
// Clean up the input values
foreach($_POST as $key => $value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Test input values for errors
$errors = array();
if(strlen($name) < 2) {
if(!$name) {
$errors[] = "You must enter a name.";
} else {
$errors[] = "Name must be at least 2 characters.";
}
}
if(!$email) {
$errors[] = "You must enter an email.";
} else if(!validEmail($email)) {
$errors[] = "You must enter a valid email.";
}
if(strlen($message) < 10) {
if(!$message) {
$errors[] = "You must enter a message.";
} else {
$errors[] = "Message must be at least 10 characters.";
}
}
if($errors) {
// Output errors and die with a failure message
$errortext = "";
foreach($errors as $error) {
$errortext .= "<li>".$error."</li>";
}
die("<span class='failure'><h3>Sorry, The following errors occured:</h3><ol>". $errortext ."</ol><a href='contact.html' class='more'>Refresh Form</a></span>");
}
// --------------------------------------//
// Send the email // INSERT YOUR EMAIL HERE
$to = "myemail#my_domain.com";
// --------------------------------------//
$subject = "Contact Form: $name";
$message = "$message";
$headers = 'From: myemail#my_domain.com' . "\r\n" .
'Reply-To: $email' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
// Die with a success message
die("<span class='success'><h3>Successfully Sent!</h3> Your message is on its way, we will respond to you shortly.</span>");
// A function that checks to see if
// an email is valid
function validEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, "#");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',
str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}
?>
I take it you are setting $email, $message etc from the $_POST or $_GET variables from your form,
e.g
$email = $_POST['email'];
This may still not work if your hosting provider has disabled the php mail() from sending emails within php.ini
Have you looked into the php pear mail function?
It may be worth simply asking your hosting provider for an example of what is allowed. It shouldn't take them more than 5 minutes to write out a sample.
Related
I'm having a difficult time getting my page to redirect after form submission. I've followed the advice that I've been able to find so far and no luck. Any help would be greatly appreciated.
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
$subject = "CONTACT FORM";
//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 sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'email#domain.com';
$body = "Name: $name \nEmail: $email";
$headers = 'From: Bond Limo (Newsletter Signup) <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) {
header("Location: http://www.website.com");
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="side-form">
Your header is not being processed. In order for your header to be processed and the redirect to occur, you will have to call the die() function after your header. Like so:
<?php
if(isset($emailSent) && $emailSent) {
header("Location: http://www.website.com");
die();
}
?>
Additionally, your code can be optimized by not checking:<?php if(isset($hasError)) { //If errors are found ?> again. Rather, just connect it with the above if statement and use an else statement like so:
// If there is no error, send the email
if (!isset($hasError)) {
$emailTo = 'email#domain.com';
$body = "Name: $name \nEmail: $email";
$headers = 'From: Bond Limo (Newsletter Signup) <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
$emailSent = mail($emailTo, $subject, $body, $headers);
} else {
// Errors found
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
}
I have some trouble with this, Anyone know why it won't work?
I have this homepage where it uses this script for sending an email, but it won't work.
When I call that I should get an email sent, but it just runs without any error.
<?php
$emailTo = 'youremail';
$siteTitle = 'SiteTitle';
//error_reporting(E_ALL ^ E_NOTICE); // hide all basic notices from PHP
//If the form is submitted
if(isset($_POST['submitted'])) {
$hasError = false;
// require a name from user
if(trim($_POST['contactName']) === '') {
$nameError = 'name plz!';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
// need valid email
if(trim($_POST['email']) === '') {
$emailError = 'Forgot Email?';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'It's not right fool';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
// we need at least some content
if(trim($_POST['comments']) === '') {
$commentError = 'Forgot something=';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
// upon no failure errors let's email now!
if(!isset($hasError)) {
$subject = 'New message to '.$siteTitle.' from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nMessage: $comments";
$headers = 'From: ' .' <'.$email.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
//Autoresponse
$respondSubject = 'Thank you for contacting '.$siteTitle;
$respondBody = "Your message to $siteTitle has been delivered! \n\nWe will answer back as soon as possible.";
$respondHeaders = 'From: ' .' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $emailTo;
mail($email, $respondSubject, $respondBody, $respondHeaders);
// set our boolean completion value to TRUE
$emailSent = true;
}
}
?>
Add \ in ', in all occurences
$emailError = 'It\'s not right fool';
instead of
$emailError = 'It's not right fool';
You need to escape any 's with \ in strings that are enclosed in 's. For example, you need to change $emailError = 'It's not right fool' to $emailError = 'It\'s not right fool'.
The same goes for "s when enclosed in "s.
You said it runs without any error, so it may not be a PHP error. Have you made sure that SMTP is set up properly on your sever? With the new code you just posted, are there any new errors?
This question already has answers here:
How to validate an Email in PHP?
(7 answers)
How to validate an email address in PHP
(15 answers)
Closed 8 years ago.
I am trying to write a script that does the following:
Prints the users message to the screen and emails it to them as well.
here is my code For some reason it tells me my email address is invalid when it is a valid email address, any suggestions? what am i missing? :-\
<?php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'post');
$errors = null;
$success = true;
function checkEmail($email){
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST){
$errors = array();
$to = $_POST['email'];
$subject = 'Your Comment';
$message = $_POST['message'];
$headers = 'From: blahblah69#gmail.com' . "\r\n" . 'Reply-To:
mitides.constantin#gmail.com' . "\r\n" .
'X-Mailer: PHP/' .phpversion();
if(!$to || !$message){
$errors[] ="Please fill in both a email and a message.";
} else if(!checkEmail($to) && $_POST['message'] = filter_var($_POST['message'],
FILTER_SANITIZE_STRING));{
$errors[]= print ('You did not enter a valid email, please try again.');
}
if($errors || !$_POST){
if($errors){
foreach($errors as $error){
echo $error. "<br />";
}
}
}
if(!$errors && $success){
mail($to, $subject, $message, $headers) && print($_POST['message']);
} ?>
at first put else if part in a bracket such like this
($_POST['message'] = filter_var($_POST['message'],FILTER_SANITIZE_STRING))
I receive my email from postmaster#domain.co.uk instead of the $email I specified.
the php should set $email as the person sending the email but It goes to the default postmaster#domain.co.uk
<?php
// Clean up the input values
foreach($_POST as $key => $value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
mb_convert_encoding($string, "UTF-8"); //AUTO DETECT AND CONVERT
mb_convert_encoding($string, "UTF-8", "latin1");
// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$telephone = $_POST["telephone"];
$pages = $_POST["pages"];
$budget = $_POST["budget"];
$message = $_POST["message"];
// Test input values for errors
$errors = array();
if(strlen($name) < 2) {
if(!$name) {
$errors[] = "You must enter a name.";
} else {
$errors[] = "Name must be at least 2 characters.";
}
}
if(!$email) {
$errors[] = "You must enter an email.";
} else if(!validEmail($email)) {
$errors[] = "You must enter a valid email.";
}
if(strlen($telephone) < 6) {
if(!$telephone) {
$errors[] = "You must enter a phone number.";
} else {
$errors[] = "Message must be at least 6 characters. (include area code)";
}
}
if(strlen($message) < 10) {
if(!$message) {
$errors[] = "You must enter a message.";
} else {
$errors[] = "Message must be at least 10 characters.";
}
}
if($errors) {
// Output errors and die with a failure message
$errortext = "";
foreach($errors as $error) {
$errortext .= "<li>".$error."</li>";
}
die("<span class='failure'>The following errors occured:<ul>". $errortext ."</ul></span>");
}
// Send the email
$to = "contact#dorsetdesigns.co.uk";
$subject = "Quote Request: $name";
$message = "Telephone Number: $telephone"."<br />"."Job Details: $message"."<br />"."Number of Pages Required: $pages"."<br />"."Clients Budget: $budget";
$headers = 'Content-Type: text/html; charset=utf-8';
"Quote Request From: $email";
mail($to, $subject, $message, $headers);
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
// A function that checks to see if
// an email is valid
function validEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, "#");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',
str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}
?>
and the js
$(function() {
// Validate the contact form
$('#contactform').validate({
// Specify what the errors should look like
// when they are dynamically added to the form
errorElement: "label",
wrapper: "td",
errorPlacement: function(error, element) {
error.insertBefore( element.parent().parent() );
error.wrap("<tr class='error'></tr>");
$("<td></td>").insertBefore(error);
},
// Add requirements to each of the fields
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
telephone: {
required: true,
minlength: 6
},
message: {
required: true,
minlength: 10
}
},
// Specify what error messages to display
// when the user does something horrid
messages: {
name: {
required: "Please enter your name.",
minlength: jQuery.format("At least {0} characters required.")
},
email: {
required: "Please enter your email.",
email: "Please enter a valid email."
},
telephone: {
required: "Please enter a phone number.",
minlength: jQuery.format("At least {0} characters required.")
},
message: {
required: "Please enter a message.",
minlength: jQuery.format("At least {0} characters required.")
}
},
// Use Ajax to send everything to quote.php
submitHandler: function(form) {
$("#send").attr("value", "Sending...");
$(form).ajaxSubmit({
target: "#response",
success: function(responseText, statusText, xhr, $form) {
$(form).slideUp("fast");
$("#response").html(responseText).hide().slideDown("fast");
}
});
return false;
}
});
});
$headers = 'Content-Type: text/html; charset=utf-8';
"Quote Request From: $email";
Should be:
$headers = 'Content-Type: text/html;\ncharset=utf-8;\nFrom: $email';
Don't have the ability to check right now, but I don't think the From address is being added to your $header variable.
$headers = 'Content-Type: text/html; charset=utf-8';
"Quote Request From: $email";
Here is an example of setting up additional headers I found on the PHP Mail Manual.
// 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";
// Additional headers
$headers .= 'To: Mary <mary#example.com>, Kelly <kelly#example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday#example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive#example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
http://www.php.net/manual/en/function.mail.php
Yours... at least according to the documentation.
$headers = 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= "From: $email" . "\r\n";
I would like to add a failed message re-direct to my mail script, so that if a user enters a wrong address in the email field it gets returned to me, and not to my hosting company's inbox, how do I do that? I've already added return-path but doesn't work, what else can i do to get this code to work.
Here is the code:
<?php if(isset($_POST['submit'])) {
if(trim($_POST['first-name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['first-name']);
}
//Check to make sure that the last name field is not empty
if(trim($_POST['last-name']) == '') {
$hasError = true;
} else {
$lname = trim($_POST['last-name']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if(!preg_match("/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure that the phone field is not empty
if(trim($_POST['tel']) == '') {
$hasError = true;
} else {
$phone = trim($_POST['tel']);
}
//Check to make sure that the phone field is not empty
if(trim($_POST['company']) == '') {
$hasError = true;
} else {
$company = trim($_POST['company']);
}
foreach (array($_POST['q1']) as $value) {
$q1 = $value[0];
$q2 = $value[1];
$q3 = $value[2];
}
//If there is no error, send the email
if(!isset($hasError)) {
$to = 'me#host.com';
$recipient = $email;
$subject = 'Subject';
$headers = "From: Me\n" . $to . "\r\n";
$headers .= "Reply-To: ". $to . "\r\n";
$headers .= "Return-Path: ". $to . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$msg1 = "First Message";
$msg2 = "Second Message";
//Send Email
mail($recipient, $subject, $msg2, $headers);
mail($to, $subject, $msg1, $headers);
$emailSent = true;
}
}
?>
the return path is set by the mta based on the envelope sender, you can't just set that in the headers yourself. You can try to set the envelope sender using the $additional_parameters argument of the mail function. See Example #3 on http://www.php.net/manual/en/function.mail.php
In your case, that would be something like
mail($recipient, $subject, $msg2, $headers, "-f $to");
On some systems overriding the envelope sender using -f is restricted. In that case you'd probably have to switch to submitting the mail via SMTP instead of calling the sendmail binary via mail().