PHP Email contact-form - php

I've recently started using HTML, Javascript and PHP to create my own website.
I have been trying to make a PHP script that takes inputs from a form, validates with javascript and php, then sends the email.
I know the script is executed and runs fine, as it sucessfully redirects me to the new page at the end. However, it does not actually send any emails for some reason.
Here is the code:
<?php
$errors = '';
$myemail = '<removed due to privacy>';
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>
Now I did see a few similar questions, but as I am very incompetent at php, they didn't really help.
If you can identify the reason, I'd be very grateful.

$sent = mail($to,$email_subject,$email_body,$headers);
put a condition like this
if($sent){ header('Location: contact-form-thank-you.html'); } else { echo 'mail failed';}
if it show "mail failed" configure your localhost to sent mails
follow this tutorials
http://blog.techwheels.net/send-email-from-localhost-wamp-server-using-sendmail/

Related

add identifier to each page on site

So my website has multiple pages where I want people to have an option to send us a message. I already have setup a php mailer but all the mails have the same layout.
How can I make to where if the message has been send form a specific page I add specific words to the mail?
The mailsender works on both the pages but the layout and everything is the same.
THIS IS THE CODE THAT WORKS FOR ME:
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$URL = $_SERVER['HTTP_REFERER'];
// Create the email and send the message
$to = 'boonwijkkermis#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "Nieuwe mail ontvangen via boonwijkkermis.com.\n\nNaam:\n $name \n\nEmail:\n $email_address \n\nTelefoon nummer:\n $phone \n\nBericht:\n$message \n\nURL:\n $URL";
$headers = "From: no-reply#boonwijkkermis.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
What you need to do is to add an hidden field in each specific page to be able to understand where the message request came from, such as:
On a page:
<input type='hidden' name='from' value='page1'>
On another page:
<input type='hidden' name='from' value='page2'>
Then in your php file check for the $_POST['from'] value to be able to tell from which page the request came from.
So you would do something like that:
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
if(!empty($_POST['from'])) { //if the from post var is not empty
if($_POST['from'] == 'page1') { //if request came from page1
$message .= " requested from page1"; //we append this text in the $message var
}
}
// Create the email and send the message
$to = 'boonwijkkermis#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "Nieuwe mail ontvangen via boonwijkkermis.com.\n\nNaam:\n $name \n\nEmail:\n $email_address \n\nTelefoon nummer:\n $phone \n\nBericht:\n$message";
$headers = "From: no-reply#boonwijkkermis.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
In alternative if you are not able to add that hidden field, you can use the $_SERVER['HTTP_REFERER'] header in your php code, that would contain the full URL from where the request came from.
This works for me
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$URL = $_SERVER['HTTP_REFERER'];
// Create the email and send the message
$to = 'boonwijkkermis#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "Nieuwe mail ontvangen via boonwijkkermis.com.\n\nNaam:\n $name \n\nEmail:\n $email_address \n\nTelefoon nummer:\n $phone \n\nBericht:\n$message \n\nURL:\n $URL";
$headers = "From: no-reply#boonwijkkermis.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

This script show me this message every time "Please fill out all the mandatory fields." [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 3 years ago.
I'm trying everything but this PHP script show this error "Please fill out all the mandatory fields."
Please help me with how to solve this problem.
<?php
session_start();
if (isset($_POST['fullname']) && isset($_POST['email']) && isset($_POST['phone'])) {
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$headers = "MIME-Version: 1.0"."\r\n";
$headers.= "Content-type:text/html;charset=UTF-8"."\r\n";
$headers.= 'From: <'.$email.'>'."\r\n";
$mailto = "google#gmail.com";
$subject = "Web Design & Development Service";
$msg2send = "Hi $fullname,
Hi, we have received one fresh query for you.
Name: $fullname
Email: $email
Phone: $phone ";
$msg2send = nl2br($msg2send);
if (mail($mailto, $subject, $msg2send, $headers)) {
echo "Thanks for writing to us. We will get back to you as soon as possible.";
} else {
echo "Please fill out all the mandatory fields.";
}
} else {
echo "Your enquiry could not be sent for some reason; please try sending us again.";
}
?>
Your if else statements are positioned incorrectly.
They point to wrong conditions.
The rearranged code:
<?php
session_start();
if (isset($_POST['fullname']) && isset($_POST['email']) && isset($_POST['phone'])) {
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$headers = "MIME-Version: 1.0"."\r\n";
$headers.= "Content-type:text/html;charset=UTF-8"."\r\n";
$headers.= 'From: <'.$email.'>'."\r\n";
$mailto = "google#gmail.com";
$subject = "Web Design & Development Service";
$msg2send = "Hi $fullname,
Hi, we have received one fresh query for you.
Name: $fullname
Email: $email
Phone: $phone ";
$msg2send = nl2br($msg2send);
if (mail($email, $subject, $msg2send, $headers)) {
echo "Thanks for writing to us. We will get back to you as soon as possible.";
} else {
// #1: Swipe with #2
echo "Your enquiry could not be sent for some reason; please try sending us again."; // Flip this with #2
}
} else {
echo "Please fill out all the mandatory fields."; // #2
}
?>
Too many nested IF statements is a bad practice because it is difficult to debug. Instead, you should break them to small statements
For example:
<?php
session_start();
if !(isset($_POST['fullname']) || isset($_POST['email']) || isset($_POST['phone'])) {
echo "Your enquiry could not be sent for some reason; please try sending us again.";
exit();
}
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$headers = "MIME-Version: 1.0"."\r\n";
$headers.= "Content-type:text/html;charset=UTF-8"."\r\n";
$headers.= 'From: <'.$email.'>'."\r\n";
$mailto = "google#gmail.com";
$subject = "Web Design & Development Service";
$msg2send = "Hi $fullname,
Hi, we have received one fresh query for you.
Name: $fullname
Email: $email
Phone: $phone ";
$msg2send = nl2br($msg2send);
if (mail($mailto, $subject, $msg2send, $headers)) {
echo "Thanks for writing to us. We will get back to you as soon as possible.";
} else {
echo "Please fill out all the mandatory fields.";
}
?>
Now the code becomes clearer and you can trace back. Seem your code has error at mail function so it return False, then the message shows up.

Send e-mail with page name in it

I currently have a contact form, from which e-mails are composed and sent using php. I use a separate php file for that.
$errors = '';
$myemail = 'mail#gmail.com';//
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']))
{
$errors .= "\n Будь ласка, заповніть усі поля";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['phone'];
$page = getRequestURI();
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "Некоректна адреса e-mail";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "Нове замовлення туру: $page".
"Деталі:\n Ім'я: $name \n Email: $email_address \n Телефон \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
I need to put such forms on different pages. And there should be information about the page on which form was submitted in the message sent by e-mail.
Is there a possibility to do that without creating separate php files for every page?
In other words how can I get the name (or url) of the page, on which form was submitted?
You can get the current request URI by using $_SERVER['REQUEST_URI'].
Assuming your script is located at http://example.com/some/page-here/more, $_SERVER['REQUEST_URI'] would be /some/page-here/more.

PHP display a html page if an error occurs in contact form output

I have a simple form with a security question to prevent spamming.
link to my webpage with the form in question http://ddry.co.uk/contact_us.html.
I want to be able to output an html page if a user inputs an incorrect answer rather than just plain text.
I have a redirect to another html file if the form is successful at the bottom of my php script. looking at other forums someone suggested using readfile("contact-failed.html#fail"); to display the html; However I'm not entirely sure where to put the code for the redirect of an incorrect answer. I'm new to PHP, so if someone is able to explain what I'm doing wrong that would great. Or alternately if somone has a better spam filter code that would be great also Thanks in advance.
html code of anti spam
php file for post.
----- UPDATE --------
I think what i'm after is an if, else statement?
after researching I have altered my code to include an else statement; However due to my lack of PHP knowledge I'm still getting a blank screen instead of my error redirect html page, which is shown at the bottom of my php code.
Question: how can I properly configure the if, else statement so if the anti-spam result is wrong (doesn't equal to 12) then proceed to contact-failed.html?
Thanks in advance
<?php
// Email address verification
function isEmail($clientEmail) {
return filter_var($clientEmail, FILTER_VALIDATE_EMAIL);}
if($_POST) {
// Enter the email where you want to receive the message
$myemail = 'info#ddry.co.uk';
$name = addslashes(trim($_POST['name']));
$clientEmail = addslashes(trim($_POST['email']));
$subject = addslashes(trim($_POST['phone']));
$phone = addslashes(trim($_POST['phone']));
$message = addslashes(trim($_POST['message']));
$antispam = addslashes(trim($_POST['antispam']));
$array = array('nameMessage' => '','emailMessage' => '', 'phoneMessage' => '', 'messageMessage' => '', 'antispamMessage' => '');
if(!isEmail($clientEmail)) {
$array['nameMessage'] = 'Empty name';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Invalid email!';
}
if($phone == '') {
$array['phoneMessage'] = 'Empty phone number!';
}
if($message == '') {
$array['messageMessage'] = 'Empty message!';
}
if($antispam != '12') {
$array['antispamMessage'] = 'Incorrect Answer!';
}
if(isEmail($clientEmail) && $clientEmail != '' && $message != '' && $antispam == '12') {
// Send email
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $clientEmail\n Message: \n $message\n Phone: $phone";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $clientEmail";
mail($to,$email_subject,$email_body,$headers);
echo json_encode($array);
header('Location: contact-success.html#success');
}
else (isEmail($clientEmail) && $clientEmail != '' && $message != '' && $antispam !== '12'){
echo('Location: contact-failed.html#fail');}
?>
Why not try something simple like this ?
function isEmail($clientEmail) {
return filter_var($clientEmail, FILTER_VALIDATE_EMAIL);
}
if($_POST){
// Enter the email where you want to receive the message
$myemail = 'info#ddry.co.uk';
$name = addslashes(trim($_POST['name']));
$clientEmail = addslashes(trim($_POST['email']));
$subject = addslashes(trim($_POST['phone']));
$phone = addslashes(trim($_POST['phone']));
$message = addslashes(trim($_POST['message']));
$antispam = addslashes(trim($_POST['antispam']));
if($antispam == '12' && isEmail($clientEmail) && $phone != '' && $message != '' ){
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $clientEmail\n Message: \n $message\n Phone: $phone";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $clientEmail";
mail($to,$email_subject,$email_body,$headers);
echo json_encode($array);
header('Location: contact-success.html#success');
}
else {
header('Location: contact-failed.html#fail');
}
My question is why you need to show another page instead of the error message in the contact form. You are redirecting to another page on success, the same can be applied on error also, you can redirect to another html page to show different version .

Contact Form in Hebrew- Weird Symbols

I made a form for contacting me on my website.
This is the php code:
<?php
$errors = '';
$myemail = 'yourname#website.com';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
"name: $name \n\n email: $email_address \n\n\n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact_thanks.html');
}
?>
When I use the form on the website, I receive a mail with weird symbols. That is because I write in Hebrew in the form- English letters are delivered well.
When I change "myemail" to another mail, the message is delivered well, even in Hebrew, but I want the message to pass to the first mail.
I changed many times the encoding, but none seems to solve the problem, perhaps I hadn't tried the correct one yet.
I am not the one who wrote the code and my I don't know php well, so please give me answers that are easy to comprehend.
You have to specify content encoding in your mail header. For this reason, add this line:
$headers .= "\nContent-type: text/html; charset=UTF-8";

Categories