What's wrong with this contact form code? - javascript

This is my code for a simple contact form. All the emails successfully get sent however when they don't enter any information the supposedly error message that should appear doesn't and it sends an email blank. As I do not wish to have spam emails, what am I doing wrong?
Code:
<?php
$field_name = $_POST['name'];
$field_email = $_POST['email'];
$field_message = $_POST['message'];
$mail_to = 'myemail#goeshere';
$subject = 'Message from client: '.$field_name;
$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Thank you for contacting us');
window.location = 'index.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('Your message failed to send due to invalid credentials.');
window.location = 'index.html';
</script>
<?php
}
?>
The HTML form:
<form method="post" action="contact.php">
<div class="row half">
<div class="6u"><input type="text" class="text" name="name" placeholder="Name" /></div>
<div class="6u"><input type="text" class="text" name="email" placeholder="Email" /></div>
</div>
<div class="row half">
<div class="12u">
<textarea name="message" placeholder="Message"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
Send Message
</div>
</div>
</form>
Sorry if the code isn't indented properly...

You don't have any code that checks if the fields are filled in. You should check that the fields are set using isset() and that they contain valid data by using things like filter_var
Also, you should not be relying on JavaScript to do redirects, If the user has JavaScript disabled this won't work. Use PHP to do your redirect.

The code always sends the email, regardless of the validation status of the form. You can, instead, check the form validation before attempting to send the email. The overall logic would look like this:
Parse user input
Are required fields valid?
Yes: Send email, display success message
No: Display error message
In the code, it might be something as simple as:
$field_name = $_POST['name'];
$field_email = $_POST['email'];
$field_message = $_POST['message'];
if ($field_email != '') {
// compose and send the email
// display success message
} else {
// display error message
}
For additional checks on the other fields, you'd add additional conditions to the if statement.

The mail function will return TRUE if the mail is accepted for delivery. Since all required parameters are present it will accept the mail even though the parameters are empty strings.
You would need to check if the input is valid or not.

Related

Contact form with PHP and HTML form [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I am trying to create a contact form using php and a html form. When the user clicks submit I want the details that they have entered into the form to be sent in an email.
When the user clicks submit they are shown a message to say the message has been sent but when I check my email nothing has been sent.
Here is my code, please note the email has been changed to show the code here.
<div id = "form">
<form action ="contact2.php" method="post">
Name:
<input type="text" name="name">
<br>
<br>
Email:
<input type="text" name="email">
<br>
<br>
Message:
<br>
<br>
<TEXTAREA NAME="message" ROWS=6 COLS=40>
</TEXTAREA>
<br>
<br>
<input type="submit" value="Submit">
</div>
</form>
<?php
$field_name = $_POST['name'];
$email = $_POST['email'];
$field_message = $_POST['message'];
$mail_to = 'example#yahoo.co.uk';
$subject = 'Message from a site visitor ' . $field_name;
$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$email."\n";
$body_message .= 'Message: '.$field_message;
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Thank you for the message. We will contact you shortly.');
window.location = 'contact.php';
</script>
else { ?>
<script language="javascript" type="text/javascript">
alert('Message failed. Please, send an email to example#yahoo.co.uk');
window.location = 'contact.php';
</script>
<?php
}?>
you want to have all that javascript wrapped in a php echo or else it doesnt work.
so...
if ($mail_status) {
echo '<script language="javascript" type="text/javascript">';
thats just a bit of the code you need to implement...
you want to echo every javascript line too.

Ajax/php contact form sending blank emails from time to time

Well I have this contact form that sends blank emails. But I did some testing and it doesn't happens to me. The only way this could happen, I think, would be by accesing the .php file directly. If not I don't know what could be the problem. The form doesn't let you send a blank email. If this keeps happening I'm going to add a validation in the php file too, but until I find out what is the problem I don't want to ignore this messages.
This is the HTML
<form name="contactForm" id="contactForm" method="post" action="/contactEngine.php" onsubmit="return validateForm()">
<input title="Input name" type="text" name="Name" id="Name" placeholder="Nombre:" required="">
<input title="Input email" placeholder="Email:" type="email" name="Email" id="Email" required="">
<input type="text" placeholder="Subject:" name="Subjet" id="Subjet">
<textarea title="Input message" placeholder="Mensaje:" name="Message" rows="20" cols="20" id="Message" required=""></textarea>
<input title="Input result" placeholder="25 + 25 = ?" type="text" name="Captcha" id="Captcha" required="">
<p id="wrongCaptcha"> Try again </p>
<input type="submit" name="submit" value="send" class="submit-button">
</form>
This is the JS
function validateForm(e) {
e.preventDefault();
var x = document.forms["contactForm"]["Captcha"].value;
if (x != 50) {//if captcha is wrong
$("#Captcha").addClass("wrongCaptchaEntered");
$("#Captcha").css("animation-name" , "none");
setTimeout (function(){
$("#Captcha").css("animation-name" , "changeBorder");
},100);
if ($("#wrongCaptcha").css("display") == "none"){
$("#wrongCaptcha").slideDown();
}
}
else { //if captcha is correct
var formAction = $("#contactForm").attr("action");
if (formAction == "/contactEngine.php"){
var formData = $("#contactForm").serialize();
$.post( formAction, formData, function(data){
console.log (data);
$(".formulario").changeTo({content: "<h2 class='section-title BackgroundGradientBlack'>"+ data +"</h2>"});
});
}
}
return false;
}
And the PHP
<?php
$EmailFrom = "EmailFrom#test.com";
$EmailTo = "EmailTo#test.com";
$Name = Trim(stripslashes($_POST['Name']));
$Email = Trim(stripslashes($_POST['Email']));
$Subject = Trim(stripslashes($_POST['Subjet']));
$Message = Trim(stripslashes($_POST['Message']));
$email_content = "Frontpage";
$email_content .= "\nNombre: $Name";
$email_content .= "\nEmail: $Email";
$email_content .= "\nMotivo: $Subject";
$email_content .= "\nMensaje: $Message";
$email_headers = "From: <$EmailFrom>";
if (mail($EmailTo, $Subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Mensaje enviado";
} else {
http_response_code(500);
echo "Error";
}
?>
Thanks!
Probably some bot that's testing the PHP endpoint it can see in your JS and is sending data to it, trying to cause havoc. I bet if you logged the $_POST variable every time an email was sent, you'd seen a lot of spammy nonsense in some $_POST variables. Emails are blank just because the bots aren't smart enough to know which keys to use in its POSTs.

Adding a Google Re-CAPTCHA form to PHP "Contact us form"

I'm a newbie in terms of web develpoment and I'm stuck with an issue with a contact form on which I'm trying to attach a captcha field to prevent spamming.
Before adding the captcha form, the code worked and the e-mails were sent.After adding the captcha validation , the JS file shows a success confirmation message but the e-mails were not sent.
Code us detailed below :
HTML:
<form name="sentMessage" id="contactForm" novalidate>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
//rest of the inputs
<div class="form-group">
<div class="g-recaptcha" data-sitekey="site_key_here"></div>
<span class="help-block" style="display: none;">Please check that you are not a robot.</span>
</div>
<br>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-success btn-lg" id="submit">Send</button>
</div>
</div>
</form>
PHP:
<?php
function errorResponse ($messsage) {
header('HTTP/1.1 500 Internal Server Error');
return false;
}
// 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 = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = '_email_here_';
$email_subject = "Contact Form from website: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply#yourdomain.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";
//MY CODE STARTS HERE
// getting the captcha
$captcha = "";
if (isset($_POST["g-recaptcha-response"])) {
$captcha = $_POST["g-recaptcha-response"];
}
else {
return false;
}
// handling the captcha and checking if it's ok
$secret = "_secret_key_here_";
$google_url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"];
$google_response = file_get_contents($google_url);
$response = json_decode($google_response, true);
// if the captcha is cleared with google, send the mail and return.
if ($response["success"] != false) {
// send the actual mail
mail($to,$email_subject,$email_body,$headers);
// return goes back to the ajax, so the user can know if everything is ok
return true;
} else {
return false;
}
//AND ENDS HERE
?>
Before the captcha validation the code was:
mail($to,$email_subject,$email_body,$headers);
return true;
The solution was found here : https://bootstrapious.com/p/bootstrap-recaptcha
Topic closed.

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.

PHP contact form modification [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
i've got a basic php script for simple contact form with name, email and message inputs.
I wish to include few more options in it but don't know how to. I've searched but couldn't find all in one solution for. I would like to:
1. Send a copy to senders email
I would like to include input for sender to have an option to receive a copy of he's submit to he's email if he checkes that input in the form.
2. Upload a file
Also if possible in the same php script i wish to give a possibility for the sender to attach a file (preferably img extensions only) when submiting a form.
3. Thank you message
Not sure about this, but now i have a simple thank you message in echo when form is submited. If possible, i wish for this message to stay visible for 5 seconds then redirect to index.html.
Here is php for the form:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="Name: $name \nEmail: $email \nMessage: $message";
$recipient = "test123#...";
$subject = "Contact";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo
"<div style='display: block; text-align: center;'>" .
"<span style='font-size: 14px;'>You message has been sent!</span>" .
"<a href='index.html'>Go back</a>" .
"</div>";
?>
and demo jsfiddle of the form setup.
Thanks for any help.
This is a global setup just to let you know how I would do this (if I wanted to do this on 1 page, but it's better to make functions, etc.)
EDIT: Please note also that I don't know if this works. Maybe there are errors but I have done this just to get you started.
<?php
//Check if form submitted
if (isset($_POST)) {
//this all will run when form is submitted
//First sanitize you data thats been posted
$name = htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8');
$email = htmlentities($_POST['email'], ENT_QUOTES, 'UTF-8');
$message = htmlentities($_POST['message'], ENT_QUOTES, 'UTF-8');
//make a error array to hold errors
$error = array();
//check if fields are not empty you can also do other checks
if (!empty($name) || !empty($email) || !empty($message))
//here you could do extra checks.. like check if emai is really a email...
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
//email invalid
array_push($error, 'email not valid');
}
//for image you could also do a if...
if(isset($_FILES)) {
$uploads_dir = 'YOUR DIR'
$name = $_FILES['image']['name'];
$type = $_FILES['image']['type'];
$size = $_FILES['image']['size'];
$temp = $_FILES['image']['tmp_name'];
$error = $_FILES['image']['error'];
if ($error === 4) {
//No file was selected
return false;
}
else
{
//do your stuff with the image here...
move_uploaded_file($temp, "$uploads_dir/$temp");
}
///you could do more ifs.. but if all is good then do the mail
$subject = 'new contact form message';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($email, $subject, $message, $headers);
$success = "here the success message";
} else {
//some fields are empty
array_push($error, 'some fields are empty');
}
?>
<!-- THE ENCTYPE IS NEEDED FOR IMAGES -->
<form action="submit.php" name="contact-form" id="contact-form" method="post" enctype="multipart/form-data">
<input name="name" placeholder="Name" type="text" id="name" required />
<input name="email" placeholder="Email" type="email" id="email" required />
<textarea name="message" placeholder="Message" id="message" required></textarea>
<input type="file" id="upload-file" accept="image/*" />
<div class="clear"></div>
<input type="checkbox" id="copy" name="copy" />
<label for="copy">Send a copy to my email</label>
<div class="clear"></div>
<input type="submit" value="Submit" form="contact-form" name="submit-form" />
</form>
<?php
if (isset($success) && !empty($success)) {
//echo the success
echo $success
}
if (isset($error) && !empty($error)) {
//loop trough error
foreach ($error as $e) {
echo $e;
}
}
?>

Categories

Resources