This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 8 months ago.
sinds a couple of days my form has stopped working.
I'm not really familiar with PHP and i have no idea how to get it working again.
I'm hosting my site on one.com , it has been working fine for about a year now, and suddenly it stopped working?
I've been searching the internet and i'm finding all kinds of answers 'you have to update your php code...' but i'm not familiar with PHP so please help :D
The form.php :
<?php
/* Set e-mail recipient */
$myemail = "info#kongweb.be";
/* Check all form inputs using check_input function */
$naam = check_input($_POST['naam']);
$mail = check_input($_POST['mail']);
$bericht = check_input($_POST['bericht']);
/* Let's prepare the message for the e-mail */
$message = "Hallo!
Wij ontvingen een contactformulier met de volgende gegevens:
Naam: $naam
E-mailadres: $mail
Message: $bericht
Einde van dit bericht.
";
/* Send the message using mail() function */
$headers = "From: info#kongweb.be";
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location:bedankt.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
And the code for the contact form on the index.html :
<!-- contact begin -->
<div id="contact" class="container-fluid text-center tekst2">
<h1>Contact</h1>
<form name="contact" method="post" action="https://kongweb.be/form.php" onsubmit="return validateForm()" >
<input type="hidden" name="subject" value="contact">
<div class="row slideanim spatieform">
<div class="col-sm-12">
<input type="text" name="naam" size="30" id="naam" required placeholder="Name">
</div>
</div>
<div class="row slideanim spatieform">
<div class="col-sm-12">
<input type="text" name="mail" size="30" id="mail" required placeholder="Email">
</div>
</div>
<div class="row slideanim spatieform">
<div class="col-sm-12">
<textarea name="bericht" id="bericht" cols="30" rows="8" required placeholder="Message"></textarea>
</div>
</div>
<div class="row slideanim spatieform">
<div class="col-sm-12">
<input type="submit" name="submit" value="Send it" style="background-color: #F3E600">
</div>
</div>
</form>
</div>
<!-- contact einde -->
This will escape your input a bit and give you some error messages for debug. Unless you are sending the email to yourself you need a $to variable and you were missing a $subject , which is also required or will not work. This is a very simple way to do this. There are lots of other like looping through the $_POST for instance. I also suggest reading https://www.php.net/manual/en/function.mail.php
Example Fix to your question:
// you can make sure its set and escape it also. Must be cleaned when user input.
if(isset('submit')){
$naam = mysqli_real_escape_string($con, $_POST['naam']);
if(!isset($coops) || empty($coops)){
$json_array['error'] = true;
$json_array['message'] = "Coops not set.";
$json = json_encode($json_array);
echo($json);
exit;
}
$mail = mysqli_real_escape_string($con, $_POST['mail']);
if(!isset($mail) || empty($mail)){
$json_array['error'] = true;
$json_array['message'] = "mail not set.";
$json = json_encode($json_array);
echo($json);
exit;
}
$bericht = mysqli_real_escape_string($con, $_POST['bericht']);
if(!isset($bericht) || empty($bericht)){
$json_array['error'] = true;
$json_array['message'] = "bericht not set.";
$json = json_encode($json_array);
echo($json);
exit;
}
$headers = "From: info#kongweb.be";
$myemail = "info#kongweb.be";
$subject = "Your subject"; // was missing and must have
$message = "Hallo!
Wij ontvingen een contactformulier met de volgende gegevens:
Naam: $naam
E-mailadres: $mail
Message: $bericht
Einde van dit bericht.";
mail($myemail, $subject, $message);
}
header('Location:bedankt.html');
exit();
are you sending the email to yourself. Otherwise you need a $to in place of you $myemail but without $subject being intialized it would never work. Redirect visitor to the thank you page
to Mail address to which you want to send mail Required
subject Subject of the mail Required
message Message to be sent with the mail. Each line of the message should be separated with a LF (\n). Lines should not be larger than 70 characters. Required
Related
Using an html form for a "contact us". This passes name, email, & message to a .php script and it works well. Add the Google recaptua v2 to this form gives a http 500 Error. This post and the code have been edited to reflect the KaplanKomputing tutorial suggested by Chris White.
You can visit the working form without recaptcha, and nonworking recaptcha here:
https://coinsandhistory.com#contact
The "Google site key" I'll call here "XXXX-Google-site" and "YYYY-Google-secret".
1st the contact form html, you don't need the css styling nor the stripslashes from the tutorial.
<!DOCTYPE html>
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer>
</script>
<link rel="stylesheet" href="../css/send-mail.css">
</head>
<body>
<!-- https://stackoverflow.com/questions/27188436/html-php-contact-form-
email/55962553 -->
<!-- https://kaplankomputing.com/blog/tutorials/
recaptcha-php-demo-tutorial/ -->
<form action="send-mail_SO2_recapt.php" method="post"
enctype="multipart/form-data" name="myemailform">
<div>
<span>Name </span>
<input type="text" name="name" value="" placeholder="Your Name">
</div>
<div>
<span>Email </span>
<input type="email" name="web_email" autocapitalize="off"
autocorrect="off"
value="" placeholder="youremail#domain.com">
</div>
<div>
<span>messgae </span>
<textarea name="message" placeholder="message"></textarea>
</div>
<!-- Google v2 Recaptua Form -->
<div class="g-recaptcha" data-sitekey="XXXX-Google-site"></div>
<br/>
<div class="code">
<button><input type="submit" name="submit" value="Send"></button>
</div>
<i class="clear" style="display: block"></i>
</div>
</form>
</body>
</html>
And then the send-mail.php script. I called mine "send-mail_SO2_recapt.php".
<?php
/* error reporting, should rmv from working form */
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST["name"];
$visitor_email = $_POST['web_email'];
$message = $_POST["message"];
$response = $_POST["g-recaptcha-response"];
//Validate first
if(empty($name)||empty($visitor_email))
{
echo "Name and email are needed!";
exit;
}
if(IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}
$url = "https://google.com/recaptcha/api/siteverify";
$data = array(
"secret" => "YYYY-Google-secret",
"response" => $_POST["g-recaptcha-response"]);
$options = array(
"https" => array (
"method" => "POST",
"content" => https_build_query($data)
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);
if ($captcha_success=>success==false) {
echo "<p>You are a bot! Go away!</p>"; }
else if ($captcha_success=>success==true) {
echo "<p>You are not not a bot!</p>"; }
// $email_from = 'info#coinsandhistory.com';//<== update the email address
$email_from = "$visitor_email";
$email_subject = "New Form submission";
$email_body = "You have received a new message from $name.\n".
"sender's email:\n $email_from\n".
"Here is the message:\n $message";
$to = "youremail#yourdomain.com"; //<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thank_you_SO2.html');
exit;
// Function to validate against any email injection attempts
?>
If you supply code samples, please indicate what form it is: eg html, php, javascript. I can't believe I'm the 1st person to try to use a simple Google recaptua in a contact form but this question doesn't appear plainly anywhere.
i see number of errors in your code. try the following code and see if it works, it is tested and working for me. it is not based on your followed tutorial and uses curl for verification instead.
Your biggest mistakes i think are that there is no isInfected function defined, => in place of -> and sometime file_get_contents doenst work on all servers.
HTML:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form action="" method="post">
<div>
<span>Name</span>
<input type="text" name="name" placeholder="Your Name" required>
</div>
<div>
<span>Email</span>
<input type="email" name="web_email" placeholder="youremail#domain.com" required>
</div>
<div>
<span>Messgae</span>
<textarea name="message" placeholder="message" required></textarea>
</div>
<!-- Google v2 Recaptcha Form -->
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
<div class="code">
<input type="submit" name="submit" value="Send">
</div>
</form>
PHP CODE:
<?php
//check form is submitted
if( isset($_POST['submit']) ){
// get values
$error = '';
$name = $_POST["name"];
$visitor_email = $_POST['web_email'];
$message = $_POST["message"];
//Validate first
if(empty($name)||empty($visitor_email)) {
$error = "Name and email are needed!";
}
//handle captcha response
$captcha = $_REQUEST['g-recaptcha-response'];
$handle = curl_init('https://www.google.com/recaptcha/api/siteverify');
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, "secret=YOUR_SECRET_KEY&response=$captcha");
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$explodedArr = explode(",",$response);
$doubleExplodedArr = explode(":",$explodedArr[0]);
$captchaConfirmation = end($doubleExplodedArr);
print_r($doubleExplodedArr);
if ( trim($captchaConfirmation) != "true" ) {
$error = "<p>You are a bot! Go away!</p>";
}
if( empty($error) ){ //no error
// mail than
$to = "youremail#mail.com";
$email_subject = "New Form submission";
$email_body = "You have received a new message from ".$name.".\n".
"sender's email:\n ".$visitor_email."\n".
"Here is the message:\n ".$message;
$headers = "From: ".$visitor_email." \r\n";
$headers .= "Reply-To: ".$visitor_email." \r\n";
//Send the email!
$mail_check = mail($to,$email_subject,$email_body,$headers);
if( $mail_check ){
// echo "all is well. mail sent";
header('Location: thank_you.html');
} else {
echo "mail failed. try again";
}
} else {
echo $error;
}
}
?>
Here is an answer which worked for me. I'd like to really thank Galzor as his answers helped me a lot. The base Code I got from Code Geek and I added stuff here to add in the form. This format hopefully eliminated the confusion on exactly what to include in the Google "SITE-KEY" and "SECRET-KEY" as it gets them as variables before processing them in a string. These are actually 40 character strings. The sucessful captcha goes to a landing page.
This is the HTML send-mail_form.html
<!DOCTYPE html>
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<!-- form goes in the body of HTML -->
<form action="send-mail_form.php" method="post">
<div>
<span>Name</span>
<input type="text" name="name" value="" placeholder="Your Name" required>
</div>
<div>
<span>Email</span>
<input type="email" name="web_email" placeholder="youremail#domain.com" required>
</div>
<div>
<span>Messgae</span>
<textarea name="message" placeholder="message" required></textarea>
</div>
<!-- Google v2 Recaptcha Form -->
<div class="g-recaptcha" data-sitekey="SITE-KEY"></div>
<div class="code">
<input type="submit" name="submit" value="Send">
</div>
</form>
</body>
</html>
And this will be the called send-mail_form.php. I won't bother with showing the thank_you_SO2.html here.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$web_email;$message;$captcha;
// check form is submitted
if(isset($_POST['web_email']) ){
// get values
$name= $_POST["name"];
$visitor_email= $_POST['web_email'];
$message= $_POST['message'];
//Validate first
if(empty($name)||empty($visitor_email)) {
$error = "Name and email are needed!";
}
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "SECRET-KEY";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' .
urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
// should return JSON with success as true
if($responseKeys["success"]) {
// echo '<h3>Thanks for contacting us</h3>';
// mail then
$to = "youremail#yourdomain.com";
$email_subject = "CG Recaptcha Form2 submission";
$email_body = "You have received a new message from ".$name.".\n".
"sender's email:\n ".$visitor_email."\n".
"Here is the message:\n ".$message;
//Send the email!
$mail_check = mail($to,$email_subject,$email_body);
if( $mail_check ){
// echo "all is well. mail sent";
header('Location: thank_you_SO2.html');
}
else {
echo '<h2>You are a spammer ! Go Away</h2>';
}
}
}
?>
There are some unneccesary items, the error checking at the top can probably be removed. Also will the Google site verify will work with https://google.com/recaptcha/api/siteverify?secret=.... ? Actually on testing it seems to fail sometimes without the www so perhaps best to keep it.
I am a complete novice when it comes to PHP. I downloaded a form I found online to include in my Bootstrap site. It is a very simple form anyone can use to send me a message. I managed to set up Wamp to test out the PHP but when I leave the Phone field blank it gives me an error message telling me please go back and correct the error. I want to make it so if someone leaves out the phone number it still sends the email. Thank you.
HTML
<form name="contactform" method="post" action="index.php" class="form-vertical">
<div class="form-group">
<label for="inputName" class="control-label">Name</label>
<input type="text" class="form-control" id="inputName" name="inputName" placeholder="First and Last">
</div>
<div class="form-group">
<label for="inputEmail" class="control-label">Email*</label>
<input type="text" class="form-control" id="inputEmail" name="inputEmail" placeholder="Required">
</div>
<div class="form-group">
<label for="inputPhone" class="control-label">Phone Number</label>
<input type="text" class="form-control" id="inputPhone" name="inputPhone" placeholder="Optional">
</div>
<div class="form-group">
<label for="inputMessage" class="control-label">Message</label>
<textarea class="form-control" rows="5" id="inputMessage" name="inputMessage" placeholder="Brief Description"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-custom pull-right hvr-underline-from-left">Send</button>
</div>
</form>
PHP
<?php
/* Set e-mail recipient */
$myemail = "myaccount#gmail.com";
/* Check all form inputs using check_input function */
$name = check_input($_POST['inputName'], "First and Last");
$email = check_input($_POST['inputEmail'], "Required");
$phone = check_input($_POST['inputPhone'], "Optional");
$message = check_input($_POST['inputMessage'], "Brief Description");
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
show_error("Invalid e-mail address");
}
/* Let's prepare the message for the e-mail */
$subject = "Contact Message from mywebsite.net";
$message = "
Someone has sent you a message using your contact form:
Name: $name
Email: $email
Phone: $phone
Message:
$message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location:contact.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>
</body>
</html>
<?php
exit();
}
?>
Please change this line:
$phone = check_input($_POST['inputPhone'], "Optional");
to:
$phone = check_input($_POST['inputPhone']);
This way show_error($problem); won't be called.
Because function check_input include function show_error.
And function show_error have exit() when have errors.
So, your phone input == NULL => so have error and call to exit().
Solution for this case
Don't check require with phone number input.
PHP
<?php
function show_error($myError)
{
?>
<html>
<body>
<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>
</body>
</html>
<?php
exit();
}
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
/* Set e-mail recipient */
$myemail = "myaccount#gmail.com";
/* Check all form inputs using check_input function */
$name = check_input($_POST['inputName'], "First and Last");
$email = check_input($_POST['inputEmail'], "Required");
$phone = $_POST['inputPhone'];
$message = check_input($_POST['inputMessage'], "Brief Description");
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Invalid e-mail address");
}
/* Let's prepare the message for the e-mail */
$subject = "Contact Message from mywebsite.net";
$message = "
Someone has sent you a message using your contact form:
Name: $name
Email: $email
Phone: $phone
Message:
$message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location:contact.html');
exit();
?>
You are facing this error because you are validating the phone number i.e $_POST['inputPhone'] using the check_input function in the line
$phone = check_input($_POST['inputPhone'], "Optional");
You can avoid this error in multiple ways:
$phone = $_POST['inputPhone']; //not secure
OR
$phone = check_input($_POST['inputPhone'], "");
OR
$phone = filter_var($_POST['inputPhone'],FILTER_SANITIZE_STRIPPED);
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I copied the message form and PHP mail from a website. But it doesn't seem to work. It does not send anything or make any reaction. I tried to find the error, but I am not familiar with PHP. I tried editing the $emailFrom =... to $_POST['email']; but that doesn't work either..
HTML:
<div id="form-main">
<div id="form-div">
<form class="form" id="form1">
<p class="name">
<input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Naam"/>
</p>
<p class="email">
<input name="email" type="text" class="validate[required,custom[email]] feedback-input" placeholder="E-mail" />
</p>
<p class="text">
<textarea name="text" class="validate[required,length[6,300]] feedback-input" placeholder="Bericht"></textarea>
</p>
<div class="submit">
<input type="submit" value="Verstuur" id="button-blue"/>
<div class="ease"></div>
</div>
</form>
</div>
</div>
PHP:
<?php
include 'functions.php';
if (!empty($_POST)){
$data['success'] = true;
$_POST = multiDimensionalArrayMap('cleanEvilTags', $_POST);
$_POST = multiDimensionalArrayMap('cleanData', $_POST);
//your email adress
$emailTo ="lisa-ederveen#hotmail.com"; //"yourmail#yoursite.com";
//from email adress
$emailFrom =$_POST['email']; //"contact#yoursite.com";
//email subject
$emailSubject = "Mail from Porta";
$name = $_POST["name"];
$email = $_POST["email"];
$comment = $_POST["comment"];
if($name == "")
$data['success'] = false;
if (!preg_match("/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email))
$data['success'] = false;
if($comment == "")
$data['success'] = false;
if($data['success'] == true){
$message = "NAME: $name<br>
EMAIL: $email<br>
COMMENT: $comment";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html; charset=utf-8" . "\r\n";
$headers .= "From: <$emailFrom>" . "\r\n";
mail($emailTo, $emailSubject, $message, $headers);
$data['success'] = true;
echo json_encode($data);
}
}
?>
Your form was incomplete, it missed the method (POST) and action (your php filename)
Try this instead:
<div id="form-main">
<div id="form-div">
<form action="sendEmail.php" method="POST" class="form" id="form1">
<p class="name">
<input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Naam"/>
</p>
<p class="email">
<input name="email" type="text" class="validate[required,custom[email]] feedback-input" placeholder="E-mail" />
</p>
<p class="text">
<textarea name="comment" class="validate[required,length[6,300]] feedback-input" placeholder="Bericht"></textarea>
</p>
<div class="submit">
<input type="submit" value="Verstuur" id="button-blue"/>
<div class="ease"></div>
</div>
</form>
</div>
</div>
sendEmail.php
<?php
//include 'functions.php';
if (!empty($_POST)){
$data['success'] = true;
//$_POST = multiDimensionalArrayMap('cleanEvilTags', $_POST);
//$_POST = multiDimensionalArrayMap('cleanData', $_POST);
//your email adress
$emailTo ="lisa-ederveen#hotmail.com"; //"yourmail#yoursite.com";
//from email adress
$emailFrom =$_POST['email']; //"contact#yoursite.com";
//email subject
$emailSubject = "Mail from Porta";
$name = $_POST["name"];
$email = $_POST["email"];
$comment = $_POST["comment"];
if($name == "")
$data['success'] = false;
if (!preg_match("/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email))
$data['success'] = false;
if($comment == "")
$data['success'] = false;
if($data['success'] == true){
$message = "NAME: $name<br>
EMAIL: $email<br>
COMMENT: $comment";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html; charset=utf-8" . "\r\n";
$headers .= "From: <$emailFrom>" . "\r\n";
mail($emailTo, $emailSubject, $message, $headers);
$data['success'] = true;
echo json_encode($data);
}
}
?>
Firstly, your form: <form class="form" id="form1">
Forms default to GET if a method isn't specifically instructed.
Use POST like this if your HTML form and PHP are inside the same file:
<form class="form" id="form1" method="post">
since you are using POST arrays.
or
<form class="form" id="form1" method="post" action="your_handler.php">
if using a different file; I used your_handler.php as an example filename.
Also, <textarea name="text"...
that should be <textarea name="comment" as per your $_POST["comment"] array.
Using error reporting would have trigged an Undefined index text... notice.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Footnotes:
I have no idea what multiDimensionalArrayMap('cleanEvilTags' does, so you'll have to check that.
If you're still not receiving mail, check your Spam.
Doing:
if(mail($emailTo, $emailSubject, $message, $headers)){
echo "Mail sent.";
}
and if it echoes "Mail sent", then mail() would have done its job. Once it goes, it's out of your hands.
You could look into using PHPMailer or Swiftmailer which are better solutions, as is using SMTP mailing.
Now, if (!empty($_POST)){ that isn't a full solution. It is best using a conditional !empty() for all your inputs. Your submit counts as a POST array and should only be relied on using an additional isset() for it.
If you're using this from your own computer, make sure that you've a Webserver installed. We don't know how your script is being used.
If you are using it from your own machine, make sure that PHP is indeed running, properly installed and configured, including any mail-related settings.
Additional notes:
You should also use full and proper bracing for all your conditional statements.
This has none:
if($comment == "")
$data['success'] = false;
which should read as
if($comment == ""){
$data['success'] = false;
}
Same thing for:
if($name == "")
$data['success'] = false;
Not doing so, could have adverse effects.
"I copied the message form and PHP mail from a website."
Again, about multiDimensionalArrayMap('cleanEvilTags'; if you don't have that function, then you will need to get rid of it and use another filter method for your inputs.
Consult the following on PHP.net for various filter options:
http://php.net/manual/en/filter.filters.php
http://php.net/manual/en/function.filter-input.php
http://php.net/manual/en/function.filter-var.php
Forgive me if this is a stupid question, but I am pretty new to PHP and I am running into some issues. I am trying to build a contact form with HTML, CSS, and PHP, but I can't seem to get my PHP form to send the contents of the form to my email address. This is what the code looks like for the HTML:
<div id="contact-form">
<ul>
<li><button id="quote" class="button1">Project Quote</button></li>
</ul>
<form class= "emai" action="mailer.php" method="post">
<p>Have a project in mind? Fill in the form for a quote!</p>
<div>
<p><label for="name">What can I call you? <span>*</span></label></p>
<input type="text" id="name" name="name">
</div>
<div>
<p><label for="email">What is your email? <span>*</span></label></p>
<input type="email" name="email" id="email">
</div>
<div>
<p><label for="type">Type of Project? <span>*</span></label></p>
<select id="type" name="type">
<option value="logo">Logo Design</option>
<option value="web dev">Website/WebApp Dev</option>
<option value="other">Other</option>
</select>
</div>
<div>
<p><label for="purpose">What is the main purpose of your project? <span>*</span></label></p>
<textarea id="purpose" name="purpose"></textarea>
</div>
<div>
<p><label for="features">Any extra features?</label></p>
<textarea id="features" name="features"></textarea>
</div>
<input class="button1" type="submit" value="submit">
</form>
</div>
And in a separate doc called "mailer.php" this is what the code looks like:
<?php
/* Set e-mail recipient */
$myemail = "christopher.kenrick#gmail.com";
$subject = "Project Request";
/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Enter your name");
$email = check_input($_POST['email']);
$type = check_input($_POST['type'], "Select a type of project");
$purpose = check_input($_POST['purpose'], "What is the purpose of your project?");
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* Let's prepare the message for the e-mail */
$message = "
Name: $name
E-mail: $email
Type: $type
Purpose: $purpose
Features: $features
Message:
$message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>
</body>
</html>
<?php
exit();
}
?>
Here is a link to my website if it will help. Can someone tell me what it is I am doing wrong?
Your code lacks proper mail headers. (and originally had a missing subject variable which you now added).
Add and modify your present mail() function with the following code, otherwise mail will be sent directly to Spam as it did for my test.
$headers = 'From: ' . $email . "\r\n";
mail($myemail, $subject, $message, $headers);
with a conditional statement:
if(mail($myemail, $subject, $message, $headers)){
echo "Success"; } else{ echo "There was a problem.";}
After running sudo apt-get install sendmail I finally started receiving the contents of the contact form. This solution should work for those using DigitalOcean as their host.
Need help in understanding why the textarea ("message" below) field in the HTML5 form is not being grabbed from the PHP code (used to create email).
HTML Code (French):
<form method="post" action="contact.php">
<fieldset>
<p class="tight" style="font-size: 10pt; text-align: center;" >Message pour des demandes de renseignements d'ordre <br /> général seulement. Veuillez utiliser demande formulaire situé <br /> sur la page Service pour commencer.</p>
<label><span>Nom</span>
<input class="inputcontact" name="name" type="text" /></label>
<label><span>Courrier <br />Électronique</span>
<input class="inputcontact" name="email" type="text" /></label>
<label><span>Téléphone</span>
<input class="inputcontact" name="telephone" type="text" /></label><br />
<label class="labelleft" for="message"> MESSAGE
<textarea name="message" rows="8" cols="45"> </textarea></label>
</fieldset>
<input class="submit" type="submit" value="ENVOYER" />
</form>
PHP Code (contact.php):
<?php
/* Set e-mail recipient */
$myemail = "xxxxxx#gmail.com";
/* Check all form inputs using check_input function */
$yourname = check_input($_POST['name']);
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$messaage = check_input($_POST["message"]);
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* Let's prepare the message for the e-mail */
$subject ="Comment received from website";
$content = "Hello!
The contact form from the website has been submitted by:
Name: $yourname
E-mail: $email
Telephone: $telephone
Message:$message
";
/* Send the message using mail() function */
mail($myemail, $subject, $content);
/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
$messaage = check_input($_POST["message"]);
Message:$message.
is it ok or misspelling?
You have a typo in your variable name $message on line 9 (you wrote $messaage).
I recommend you to use filter_var($email, FILTER_VALIDATE_EMAIL); instead of your Regex. I think this would be more specific