PHP Contact form submits without needing all fields filled in - javascript

I have a PHP contact form which works even if the fields are not filled in. This hasn't been a problem until recently when I've started to get handfuls of blank emails every day.
How do enforce all fields to be filled out in the form before the submit button can be used?
Here is my PHP code below:
<?php
header("Access-Control-Allow-Origin: *");
$EmailFrom = "myemail";
$EmailTo = "myemail";
$Subject = "subject goes here";
$Email = Trim(stripslashes($_POST['email']));
$Message = Trim(stripslashes($_POST['message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom" . "\r\n" );
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
And here is my HTML markup:
<!-- CONTACT FORM -->
<div class="span9 contact_form">
<div id="note"></div>
<div id="fields">
<div id="post-ajax" style="display: none;"></div>
<form id="contact-form-face" class="clearfix" action="/php/contactengine.php">
<input type="text" name="email" value="Email" onFocus="if (this.value == 'Email') this.value = '';" onBlur="if (this.value == '') this.value = 'Email';" />
<textarea name="message" onFocus="if (this.value == 'Message') this.value = '';" onBlur="if (this.value == '') this.value = 'Message';">Message</textarea>
<input class="contact_btn" name="submit" type="submit" value="Send Message" />
</form>
</div>
</div>
<!-- //CONTACT FORM -->

I can't find your fields. But in general, HTML5 provides a very convenient way to make a form field required. To do so, you can add a required attribute in your form elements, such as:
<input type="text" name="txt_name" required />
Modern browsers will validate the fields during form submit. To support older browsers, you can use JS validation libraries for client-side validation and use PHP condition check, e.g. if(!empty($_POST['txt_name'])) for server-side validation.
Moreover, it is suggested not to use meta refresh tag for redirection; use header('Location: error.htm'); exit; for example, instead.
<!-- CONTACT FORM -->
<div class="span9 contact_form">
<div id="note"></div>
<div id="fields">
<div id="post-ajax" style="display: none;"></div>
<form id="contact-form-face" class="clearfix" action="/php/contactengine.php">
<input type="text" name="email" value="Email" onFocus="if (this.value == 'Email') this.value = '';" onBlur="if (this.value == '') this.value = 'Email';" required />
<textarea name="message" onFocus="if (this.value == 'Message') this.value = '';" onBlur="if (this.value == '') this.value = 'Message';" required>Message</textarea>
<input class="contact_btn" name="submit" type="submit" value="Send Message" />
</form>
</div>
</div>
<!-- //CONTACT FORM -->

Apart from adding the required attribute as indicated in the other answer(which can be by passed very easy through inspect element) you also need validation in the server side as well before processing.
You can create an array of the required fields then check, if those fields are set and not empty.
<?php
$errors = "";
$requiredFields = array("email","message"); // enter the name in the inputs, ie name="someInput"
foreach($requiredFields as $fieldname){
if(!isset($_POST[$fieldname]) && empty($_POST[$fieldname])){
$errors++;
echo "Enter all fields";
//OR redirect to error page
}
}
if($errors <=0){
// Proccess the form
$EmailFrom = "myemail";
$EmailTo = "myemail";
$Subject = "subject goes here";
$Email = Trim(stripslashes($_POST['email']));
$Message = Trim(stripslashes($_POST['message']));
// prepare email body text
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom" . "\r\n" );
// redirect to success page
if ($success){
header("location:contactthanks.php");
exit();
}
else{
header("location:error.htm")
exit();
}
}
?>

Related

How do I fix the POST 405 error for an email form (PHP) hosted on http-server?

I am new to PHP and jQuery. I wanted to test the functionality for the email contact form in PHP that I call from my jQuery file. I have been filling in the details on the form correctly, however, whenever I press the "Submit" button, I get 405 error.
To be more precise, I get "POST http://192.168.87.1:8080/js/inc/contactformhandler.php 405 (Method Not Allowed)" from jquery-3.4.1.min.js:2. I am running my website on http-server !.
My HTML form:
<div class="row contact-form">
<div class="col-twelve">
<!-- form -->
<form name="contactForm" id="contactForm" method="POST">
<fieldset>
<div class="form-field">
<input name="contactName" type="text" id="contactName" placeholder="Name" value="" minlength="2" required="">
</div>
<div class="form-field">
<input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="">
</div>
<div class="form-field">
<input name="contactSubject" type="text" id="contactSubject" placeholder="Subject" value="">
</div>
<div class="form-field">
<textarea name="contactMessage" id="contactMessage" placeholder="message" rows="10" cols="50" required=""></textarea>
</div>
<div class="form-field">
<button class="submitform">Submit</button>
<div id="submit-loader">
<div class="text-loader">Sending...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
</fieldset>
</form> <!-- Form End -->
<!-- contact-warning -->
<div id="message-warning">
</div>
<!-- contact-success -->
<div id="message-success">
<i class="fa fa-check"></i>Your message was sent, thank you!<br>
</div>
</div> <!-- /col-twelve -->
</div> <!-- /contact-form -->
JS code where I try to load the contactformhandler.php:
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('#submit-loader');
$.ajax({
type: "POST",
url: "js/inc/contactformhandler.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.fadeIn();
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
sLoader.fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
},
error: function() {
sLoader.fadeOut();
$('#message-warning').html("Something went wrong with loader. Please try again.");
$('#message-warning').fadeIn();
}
});
}
});
contactformhandler.php:
<?php
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
// Replace this with your own email address
$siteOwnersEmail = 'krysbaran#gmail.com';
if(isset($_POST["submit"])) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'MyWebsiteEmail';
$mail->Password = 'MyPassword';
$mail->SMTPSecure = 'ssl'; //<---- THIS is the problem
$mail->Port = 465;
$mail->setFrom('MyWebsiteEmail', 'My Website');
$mail->addAddress($siteOwnersEmail, 'Krzysztof Baran');
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = 'test text';
try {
$mail->send();
echo 'OK';
}
catch (phpmailerException $e) {
echo $e->errorMessage();
} catch (Exception $e) {
$e->getMessage();
}
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
I expect the website to display box saying Your message was sent, thank you! but I am getting Something went wrong with loader. Please try again.
You should use form in .php file not in .html file

PHP Notice: Undefined index: Name in {project Folder}/contact/contactengine.php on line 6

I hope that you can help me with a problem that I have. I have a contact form, and I am getting an error log like this:
PHP Notice: Undefined index: Name in {path}/contactengine.php on line 6
PHP Notice: Undefined index: Email in {path}/contactengine.php on line 7
PHP Notice: Undefined index: Message in {path}/contactengine.php on line 8
my PHP code and HTML are:
<?php
$EmailFrom = "";
$EmailTo = "admin#memwdesings.com";
$Subject = "From website";
$Name = Trim(stripslashes($_POST['Name'])); // line 6
$Email = Trim(stripslashes($_POST['Email'])); // line 7
$Message = Trim(stripslashes($_POST['Message']));// line 8
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=http://arquitectura-om.com/\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
<!-- Contact Form -->
<div class="col-md-5">
<div class="contact-header">Send us a Message</div>
<form method="post" action="contact/contactengine.php">
<div class="control-group form-group">
<div class="controls">
<label>Name:</label>
<input type="text" class="form-control" id="Name" required data-validation-required-message="Please enter your name.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Email:</label>
<input type="email" class="form-control" id="Email" required data-validation-required-message="Please enter your email address.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Message:</label>
<textarea rows="10" cols="100" class="form-control" id="Message" required data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="contact-btn btn">Send Message</button>
</form>
</div>
No name attributes in your form fields means no values submitted.
id attributes don't count.
Basically, if you don't need the id attribute for css, js, or the labels, just replace id with name.
Give your submit button a name submit and put all php code inside a if condition in contactengine.php file like
if(isset($_POST['submit'])){
print_r($_POST);
}
Hi you have not given the name attribute of form elements submitted.
You have to give name of each form element and then use that name to get values in submitted action of form like in $_POST['name']

Fix contact form - Messages sent successfully

I have a landing page in HTML that involves sending data via a contact form. But if you try to use the contact form, when you click the 'Submit' button, you open a new PHP page with 'Success'. How can I do that when I click 'Submit' does not open a page, but a text appears under the 'Send' button with the text 'Messages sent successfully'?
I cannot fix this problem. What should I change in my HTML and my PHP?
Here is an example image of what I would like to do:
HTML CODE:
<!-- Form -->
<form class="contact-form" role="form" method="post" action="php/form-process.php">
<i class="mdi-action-account-box"></i>
<input type="text" class="form-control" name="name" placeholder="Nome" required="required">
<i class="mdi-content-mail"></i>
<input type="email" class="form-control" name="email" placeholder="Email" required="required">
<textarea class="form-control" name="message" placeholder="Messaggio" rows="4" required="required"></textarea>
<input type="checkbox" name="trattdati" required /> Accetto il trattamento dei miei dati ai sensi del D.Lgs. 196/03<br />
<input type="checkbox" name="provasoftware" /> Desidero provare il software
<br /><br />
<button type="submit" id="submit" class="btn btn-lg btn-primary"
style="float:left">Invia</button>
<div id="success" class="success" style=" color: #009688;
font-size: 20px;
margin-top: -16px;
float: left;
margin-left: 25px;">
</div>
</form>
<script>
$(document).ready(function() {
// This command is used to initialize some elements and make them work properly
$.material.init();
var options = {
target: '#success', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
// pre-submit callback
function showRequest(formData, jqForm, options) {
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
$('.contact-form')[0].reset();
$('.contact-form').trigger("reset");
}
// bind form using 'ajaxForm'
$('.contact-form').ajaxForm(options);
});
</script>
PHP FILE:
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// MSG SUBJECT
//if (empty($_POST["msg_subject"])) {
// $errorMSG .= "Subject is required ";
//} else {
// $msg_subject = $_POST["msg_subject"];
//}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "bagiacchimarco7#gmail.com";
$Subject = "New Message Received";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
//$Body .= "Subject: ";
//$Body .= $msg_subject;
//$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
Assuming you are using the Javascript correctly as per the documentation for whatever plugin you are using, you should be able to simply do:
function showResponse(responseText, statusText, xhr, $form) {
$('#success').html(responseText);
$('.contact-form')[0].reset();
$('.contact-form').trigger("reset");
}
Again, I'm making assumptions, but responseText should contain the data from your PHP page. #success looks like the div where you want your form feedback to go and the html jQuery function will allow you to put the responseText into the #success div.
Granted the other answers all show ways of doing this without your plugin, but it appears you are using a jQuery plugin.
EDIT
After reading the documentation on your plugin I think you may just need to add:
$('.contact-form').submit(function() {
// submit the form
$(this).ajaxSubmit();
// return false to prevent normal browser submit and page navigation
return false;
});
You need to thoroughly read the documentation about all of the plugins you are using.
EDIT2
Try changing Raj's code to
$('#submit').click(function(e){
e.preventDefault() //Prevent the default action of the form.
$.post( //Send a POST request to the PHP file via AJAX
"php/form-process.php", //Path to the PHP file where you want to send the POST
$(.contact-form).serializeArray().reduce(function(obj, item) {
obj[item.name] = item.value;
return obj;
}, {}), // This takes all the form fields and returns key-value pairs of form data
function (data) { //data = response from the PHP file. In your case "Sucess"
if(data==="success"){
//do something with data. Have assumed you want to append it to a div called "response". You will need to add <div id="success"> </div> below your form
$('#success').html(data);
} else {
$('#success').html("Sorry Try Again");
}
});
)}
You need to send a POST request via AJAX to your PHP file and handle the response on the DOM.
jQuery/AJAX code
$('#submit').click(function(e)
e.preventDefault() //Prevent the default action of the form.
$.post( //Send a POST request to the PHP file via AJAX
"path/to/file.php", //Path to the PHP file where you want to send the POST
$(.contact-form).serializeArray().reduce(function(obj, item) {
obj[item.name] = item.value;
return obj;
}, {}) // This takes all the form fields and returns key-value pairs of form data
, function (data) { //data = response from the PHP file. In your case "Sucess"
if(data==="success"){
//do something with data. Have assumed you want to append it to a div called "response". You will need to add <div id="response"> </div> below your form
$('#response').html(data);
} else {
$('#response').html("Sorry Try Again");
}
//Alternatively you can just append data to response and not have this IF
});
)
Also do check out validate.js. It handles validation of the form on the front end itself and also has a really nice method to submit forms and manage responses.
You could use if submit button was clicked and all filled out then redirect to success_page.php Just add name="submit" and it should work HTML:
UPDATE 2 : Working Example --->> sample website (DOnt mind the errors its just a quick example you can play around with it yourself. I added the php into the html file and it work. Hopfully this will help you.
UPDATE: If you include your php page in the div you want it should print out the message.
<form class="contact-form" role="form" method="post" action="">
<i class="mdi-action-account-box"></i>
<input type="text" class="form-control" name="name" placeholder="Nome" required="required">
<i class="mdi-content-mail"></i>
<input type="email" class="form-control" name="email" placeholder="Email" required="required">
<textarea class="form-control" name="message" placeholder="Messaggio" rows="4" required="required"></textarea>
<input type="checkbox" name="trattdati" required /> Accetto il trattamento dei miei dati ai sensi del D.Lgs. 196/03<br />
<input type="checkbox" name="provasoftware" /> Desidero provare il software
<br /><br />
<button type="submit" id="submit" class="btn btn-lg btn-primary" style="float:left">Invia</button>
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// MSG SUBJECT
//if (empty($_POST["msg_subject"])) {
// $errorMSG .= "Subject is required ";
//} else {
// $msg_subject = $_POST["msg_subject"];
//}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "bagiacchimarco7#gmail.com";
$Subject = "New Message Received";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
//$Body .= "Subject: ";
//$Body .= $msg_subject;
//$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success message sent!";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
<div id="success" class="success" style=" color: #009688;
font-size: 20px;
margin-top: -16px;
float: left;
margin-left: 25px;">
</div>
</form>

Ajax form taking a very long time to send emails

I have an Ajax contact form on my site which actually currently works but the email that it compiles from the form is taking around 50 minutes to arrive in my inbox, here is the code, does anyone know what could be causing this excessive time gap?
Jquery
$("#contactForm").submit(function(event){
// cancels the form submission
event.preventDefault();
submitForm();
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
}
function formSuccess(){
$( "#msgSubmit" ).removeClass( "hidden" );
}
HTML
<div id="form-container">
<form role="form" id="contactForm">
<input id="name" class="input" type="text" placeholder="Your name" name="name">
<input id="email" class="input" type="text" placeholder="Contact email address" name="email">
<textarea id="message" class="input message" placeholder="What would you like to discuss?" name="message"></textarea>
<input id="form-submit" class="submit" type="submit" value="Send Message" name="submit">
</form>
</div>
PHP
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$EmailTo = "contact#etcetcetc.co.uk";
$Subject = "New Message Received";
// prepare email body text
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success){
echo "success";
}else{
echo "invalid";
}
?>

PHP contact form will just refresh the page after submission.

After searching for about 3 hours i still can't figure this one out.
I Have a html template with a contact form and im trying to make it work using a PHP script.
I changed the template to PHP and pasted the PHP form script in it. everything is working fine except the confirmation text.
After a successful submission it will just refresh the page instead of printing "Your mail has been sent successfuly ! Thank you for your feedback". i do not want a redirect, i just want it to print on the same page.
Any ideas?
I got a sample of my code.
<form action="<? echo $_SERVER['PHP_SELF']; ?>" id="contact-form" method="post" class="form afsana-form" role="form">
<div class="row">
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="name" name="name" placeholder="name" type="text" required autofocus />
</div>
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="email" name="email" placeholder="email" type="email" required />
</div>
<div class="col-sm-12 form-group">
<textarea class="form-control" id="message" name="message" placeholder="message" rows="5"></textarea>
</div>
<div class="col-sm-12 form-group">
<button class="btn btn-primary afsana-btn" name="submit" value="verzenden" type="submit">Verzenden <i class="ion-arrow-graph-up-right"></i></button>
</div>
</div>
</form>
<?php
if(isset($_POST["submit"])){
// Checking For Blank Fields..
if($_POST["name"]==""||$_POST["email"]==""||$_POST["message"]==""){
echo "Fill All Fields..";
}else{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['email'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email){
echo "Invalid Sender's Email";
}
else{
$subject = (Contact_form);
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$headers .= 'Cc:'. $email2 . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// Send Mail By PHP Mail Function
mail("something#domain.com", $subject, $message, $headers);
echo "Your mail has been sent successfuly ! Thank you for your feedback";
}
}
}
?>
First, you have this: $subject = (Contact_form); which should throw an error, so I assume you have error reporting turned off. When developing, you should have error reporting on so you can see errors in your code... Else you are just working blind. I don't mean by throwing tacky error_reporting(0) in every file either, I mean to set your error reporting level to E_ALL in your php.ini.
You also have: $headers .= 'Cc:'. $email2 . "\r\n";
However, $email2 is not defined anywhere, so you would get an error here too.. which is why it's important to test with error reporting on.
See if this works:
<?php
$error = '';
if(isset($_POST['submit']))
{
if ( !empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message']) )
{
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if ( $email = filter_var($email, FILTER_VALIDATE_EMAIL) )
{
$subject = '(Contact_form)';
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$message = wordwrap($message, 70);
if ( $result = mail("something#domain.com", $subject, $message, $headers) ) {
$error = 'Success';
} else {
$error = 'There was an error sending your email!';
}
} else {
$error = 'Invalid Email Address!';
}
} else {
$error = 'Please fill all fields.';
}
}
?>
<p><?= $error ?></p>
<form action="" method="post">
<input type="text" name="name" value="" /><br />
<input type="email" name="email" value="" /><br />
<textarea name="message" rows="5"></textarea><br />
<input type="submit" name="submit" value="submit" />
</form>
Try to put in $subject just a string value like:
$subject = 'Test subject';
change also the following line to this (there is no $email2 defined):
$headers .= 'Cc:'. $email . "\r\n"; // Carbon copy to Sender
and give it a try. You can also put as first line of your code
<?php error_reporting(E_ALL); ?>
and check for errors when submiting the form.

Categories

Resources