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 :)
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?
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 7 years ago.
So have a single form which only gets the email of the person and sends it to the email address I assigned. But I guess I wrote the code in a wrong way since I am getting errors. I have seen other stackoverflow problems but I am not sure why this isnt working.
This is the form in html.
<form style="margin-bottom:50px;" name="contactform" action="contact-form-handler.php" class="news-letter "method="post">
<div class="subscribe-hide">
<input type="text" name="email" class="form-control" placeholder="Email Address" >
<button type="submit" class="btn"><i class="fa fa-envelope"></i></button>
</div><!-- /.subscribe-hide -->
</form><!-- /.news-letter -->
and here is the PHP code in a different file.
<?php
$errors = '';
$myemail = 'masnadhossain#live.com';
empty($_POST['email']))
{
$errors .= "\n Error: all fields are required";
}
$email_address = $_POST['email'];
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";
$email_body = "You have received a new message. ".
" Here are the details:".
"Email: $email_address\n ";
$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');
}
?>
The error I get is server error 500
Your code have syntax error pleas check it.
Line no 3 should be:
if (empty($_POST['email']))
{
$errors .= "\n Error: all fields are required";
}
1.) The first problem you have is that you are sending the email address from a form input via post but you did not utilize it.
2.) To and From variables are having the same email address masnadhossain#live.com which is creating conflicts
3.) The Preg_Match for checking Email address validity is errorneous. I have re-written your code below.
If you are posting the users email(eg gmail,yahoomail etc) from a form input, this code will get you going.
In case you want to intialize the email within the code just change
$email_address = strip_tags($_POST['email']);
to may be
$email_address = 'user1#gmail.com';
Finally, the From variable must be the email address pointing to your website address. in this case I think it is masnadhossain#live.com
This code is working. please mark it as correct answer if it solve your problem....
<?php
//Users email address coming from form input eg. gmail,yahoomail etc.
$email_address = strip_tags($_POST['email']);
//validate the email address
$email_val= filter_var($email_address, FILTER_VALIDATE_EMAIL);
if (!$email_val){
echo "<font color=red><b>Invalid Email Address</b></font>";
exit();
}
$to=$email_val;
$subject = "Contact form submission";
$message = "Here is the message;
// set the from variable to any email pointing to your website
$from = "masnadhossain#live.com";
$headers = "From:" . $from;
$sent=mail($to,$subject,$message,$headers);
if($sent) {
print "<br><font color=green><b>Your mail was sent Successfully</b></font>";
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
} else {
print "<br><font color=orange><b>We encountered an error sending your mail.</b></font>";
}
?>
I am a complete novice when it comes to php, I have got the below php which sends me back the 'message' and sends an auto response to the user, as well as redirecting them to the 'thank you' page. Problem I am having is that it won't return the users name that they fill in on the form, any ideas?
<?php
$youremail = "ally.baird81#gmail.com"; //this is where the email will be sent to
#extract($_POST);$name = filter_var($name, FILTER_SANITIZE_STRING);
$message = filter_var($message, FILTER_SANITIZE_STRING);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (mail($youremail, 'Message from website.', $message, "From: Krew Kut Hair<$email>")) {
$autoreply = "Thank you for enquiring at Krew Kut Hair, we will be in contact shortly";
$subject = "Thank you for your enquiry!";
mail($email, $subject, $autoreply, "From: Krew Kut Hair<$email>");
}
} else {
echo "Please enter a valid email address";
}
header("Location: thanks.html");
Assuming the name is in one of the form fields, you should be able to retrieve it. As Barmar says - all you have to do is use it somewhere in the body or the message. How can you tell the name is missing if you don't echo it out somewhere.
Try this:
$autoreply = "Thank you ".$name." for ...
If the name is still "missing" - you can try to see all the post variables like this:
echo "<PRE>Post Vars\n"; print_r($_POST);
If you have an input named "name" like:
<input type="text" name="name" value="" />
Check if it's containing data with e.g. :
echo 'The value of name is ['.$name.']';
If it is containing data you just can use the $name variable in your message. If it isn't there is probably something wrong in your HTML form.
<?php
$youremail = "ally.baird81#gmail.com"; //this is where the email will be sent to
#extract($_POST);$name = filter_var($name, FILTER_SANITIZE_STRING);
$message = filter_var($message, FILTER_SANITIZE_STRING);
$content = "<strong>Name:<strong><br />".$name."<br />";
$content .= "<strong>Message:<strong><br />".$message."<br />";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (mail($youremail, 'Message from website.<br />', $content, "From: Krew Kut Hair<$email>")) {
$autoreply = "Hi ".$name.". Thank you for enquiring at Krew Kut Hair, we will be in contact shortly";
$subject = "Thank you for your enquiry!";
mail($email, $subject, $autoreply, "From: Krew Kut Hair<$email>");
}
} else {
echo "Please enter a valid email address";
}
header("Location: thanks.html");
Also read the comments on your question. I strongly recommend to find an other way instead of using extract().
I'm using code from another source but it's very different to what I'm used to coding when using standard HTML/PHP websites. Wordpress seems to have a mind of it's own. Basically I need the contact form's PHP to send the name and email within the body text of the email and not just the persons message. Currently all that comes through is the persons message.
<?php
//response generation function
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message){
global $response;
if($type == "success") $response = "<div class='success'>{$message}</div>";
else $response = "<div class='error'>{$message}</div>";
}
//response messages
$not_human = "Human verification incorrect.";
$missing_content = "Please Fill in all Required Fields.";
$email_invalid = "Your Email Address is Invalid.";
$message_unsent = "Message was not sent. Please Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$message = $_POST['message_text'];
$human = $_POST['message_human'];
//php mailer variables
$to = get_option('admin_email');
$subject = "New Enquiry Through Mon Voyage Website";
$headers = 'From: '. $email . "\r\n" .
'Reply-To: ' . $email . "\r\n";
if(!$human == 0){
if($human != 2) my_contact_form_generate_response("error", $not_human); //not human!
else {
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
my_contact_form_generate_response("error", $email_invalid);
else //email is valid
{
//validate presence of name and message
if(empty($name) || empty($message)){
my_contact_form_generate_response("error", $missing_content);
}
else //ready to go!
{
$sent = wp_mail($to, $subject, strip_tags($message), $headers);
if($sent) my_contact_form_generate_response("success", $message_sent); //message sent!
else my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
}
}
}
}
else if ($_POST['submitted']) my_contact_form_generate_response("error", $missing_content);
?>
Any ideas?
add this in just before if(!$human == 0){:
$message.='Name: '.$name.'email: '$email;
this is all standard php form checking, 1. function to display a reponse 2. check the $_POST data 3. fail if errors in place 4. if no errors, send email. Put a few echo's in there and play around with it to see what is happening.
This does not solve the issue you are having directly but instead of writing the code yourself you could use Contact form 7 plugin instead. It will save you time and is very quick to implement.
You can get the plugin from this url.
Here is the documentation for implementing the plugin.
You can add a contact form by adding the short code generated by the plugin to the page you want it to appear like this:
[contact-form-7 id="1234" title="Contact form 1"]
I have the below PHP contact form that has a CAPTCHA code to ensure is correct. However, when I reply to the email from the website it puts a random email which i believe is the server admin, however, I want it to be the persons email who sent the form in. below is the code, could you possibly be able to help me?
<?php session_start();
if(isset($_POST['Submit'])) { if( $_SESSION['chapcha_code'] == $_POST['chapcha_code'] && !empty ($_SESSION['chapcha_code'] ) ) {
$youremail = 'info#example.com';
$fromsubject = 'www.example.co.uk';
$title = $_POST['title'];
$fname = $_POST['fname'];
$mail = $_POST['mail'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = $youremail;
$mailsubject = 'Message from Website'.$fromsubject.' Contact Page';
$body = $fromsubject.'
The person that contacted you is: '.$fname.'
Phone Number: '.$phone.'
E-mail: '.$mail.'
Subject: '.$subject.'
Message:
'.$message.'
|---------END MESSAGE----------|';
echo "Thank you for your message. I will contact you shortly if needed.<br/>Go to <a href='/index.html'>Home Page</a>";
mail($to, $subject, $body);
unset($_SESSION['chapcha_code']);
} else {
echo 'Sorry, you have provided an invalid security code';
}
} else {
echo "You must write a message. </br> Please go to <a href='/contact.html'>Contact Page</a>";
}
?>
You'll need some headers so the from address is the users mail.
Also refer to the mail docs
try this
$headers = "From: $mail\r\n";
$headers .= "Reply-To: $mail\r\n";
mail($to, $subject,$body,$headers);