HTML5 Contact form is submitting without any data in fields - php

My first time posting here so apologies if i get anything wrong. I have recently built a site from a HTML5 UP template - www.vancareleeds.co.uk. I have used the contact form that came with the template and used a simple mail.php file in the root folder to action the email to be sent to my inbox.
I have also put in Google ReCaptcha but am since struggling to force the form to validate (EG. the form can be sent without the reCaptcha being ticked and it can also be sent with no information in the fields on the form.
I have provided my code here of the .php and also the webpage itself.
If i have broken protocol or best practice for psots i apologise.
mail.php
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$mobile = $_POST['mobile'];
$vehicle = $_POST['category-vehicle'];
$service = $_POST['category-service'];
$formcontent="From: $name \n Message: $message \n Mobile: $mobile \n Vehicle: $vehicle \n Service Required: $service";
$recipient = "info#vancareleeds.co.uk";
$subject = "Contact Form from VanCare Website";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!";
?>
form html
<form method="post" action="mail.php">
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</div>
<div class="field">
<label for="email">Email</label>
<input type="email" name="email" id="email" />
</div>
<div class="field">
<label for="message">Message</label>
<textarea name="message" id="message" rows="4"></textarea>
</div>
<div class="g-recaptcha" data-theme="dark" class="g-recaptcha" data-sitekey="6Lf1OVMUAAAAAJv1fNtt-CJEFPK-Q0Ugc1CVCRVh"></div><br/>
<ul class="actions">
<li><input type="submit" value="Send Message" /></li>
</ul>
</form>

Welcome +Catalan Soccer! I would suggest to you if you are new to PHP to use var_dump(), print_r() or var_export() the result of the $_POST global array to see what was sent to your PHP script. All other things you can comment out and uncomment if you feel confident.
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['name'], $_POST['email'], $_POST['message']) === true) {
$name = filter_var(trim($_POST['name']), FILTER_SANITIZE_STRING);
if (empty($name) === true) {
$errors['name'][] = 'Name is empty';
} elseif (ctype_alpha($name) === false) {
$errors['name'][] = 'Name contains invalid characters';
}
$email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
if (empty($email) === true) {
$errors['email'][] = 'E-mail is empty';
} elseif ($email === false) {
$errors['email'][] = 'Invalid e-mail address';
}
$message = strip_tags(trim($_POST['message']));
if (empty($message) === true) {
$errors['message'][] = 'Message is empty';
}
if (count($errors) === 0) {
echo 'Thank you!';
// you can use here the sanitized user input to send the e-mail
}
}
if (count($errors) > 0) {
foreach ($errors as $field => $messages) {
echo implode(', ', $messages), '<br>';
}
}
This will test user input and print out error message.

Related

HTML/PHP Contact form sending many emails and "Confirm form resubmission" keeps popping up [duplicate]

This question already has answers here:
How to prevent form resubmission when page is refreshed (F5 / CTRL+R)
(21 answers)
PHP Inserting Duplicates In DB
(1 answer)
Closed 4 years ago.
So I'm working on my website and come to a place where I added a contact form. I got it working, it is sending emails to my server mail but I'm keep getting same email each time I reload the site and here comes the second problem. When I press F5 button I'm getting an alertbox with "Confirm form Resubmission" "The page that you're looking for used information that you entered. Returning to that page might cause any action you took to be repeated. Do you want to continue?"
I tried to do my best but couldn't change it, could someone explain what is wrong in my code? Thanks a lot for your time answering me!
<?php
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == ''){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'admin#xxxx.xxx';
$subject = $email;
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
$name = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
AND HTML :
<form id="contact" action="<?= htmlspecialchars($_SERVER[" PHP_SELF "]) ?>" method="post">
<h3>Contact me</h3>
<h4>Just send me an email and I will respond as fast as I can!</h4>
<fieldset>
<input placeholder="Your name" type="text" name="name" value="<?= $name ?>" tabindex="1" autofocus>
<span class="error"><?= $name_error ?></span>
</fieldset>
<fieldset>
<input placeholder="Your Email Address" type="text" name="email" value="<?= $email ?>" tabindex="2">
<span class="error"><?= $email_error ?></span>
</fieldset>
<fieldset>
<textarea value="<?= $message ?>" name="message" tabindex="3">
</textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
<div class="success">
<?= $success ?>
</div>
</form>

php form not validatin or sending mails

I a trying to fix a php form that doesn't work
I am new to php, please help
I have the form in the index.html file and have another validation.php to validate the form fields.
<!-- contact form --->
<div class="containerq">
<div class="form_container">
<h2 class="text-center">Contact us</h2>
<form action="index.php" method="post" class="rd-mailform">
<input type="hidden" value="contact" name="form-type">
<fieldset>
<div class="row">
<div class="col-md-prefix-1 col-md-12">
<label data-add-placeholder="" class="mfInput">
<input type="text" name="name" placeholder="Name">
</label>
</div>
<div class="col-md-prefix-1 col-md-12">
<label data-add-placeholder="" class="mfInput">
<input type="text" name="email" placeholder="Email">
</label>
</div>
<div class="col-md-prefix-1 col-md-12">
<label data-add-placeholder="" class="mfInput">
<input type="text" name="phone" placeholder="Phone">
</label>
</div>
<div class="col-md-prefix-1 col-md-12">
<label data-add-placeholder="" class="mfSelect">
<select class="opt">
<option>Choose subject</option>
<option>I have a problem with a game</option>
<option>I have a problem with a course</option>
<option>I have an Idea</option>
<option>Collaboration with schools</option>
<option>Collaboration with game developers</option>
<option>General query and other subjects</option>
</select>
<ul class="dropdown">
<li class="option">I have a problem with a game</li>
<li class="option">I have a problem with a course</li>
<li class="option">I have an Idea</li>
<li class="option">Collaboration with schools</li>
<li class="option">Collaboration with game developers</li>
<li class="option">General query and other subjects</li>
</ul><span class="mfPlaceHolder"></span>
</label>
</div>
<div class="col-md-prefix-1 col-md-12">
<label data-add-placeholder="" class="mfInput">
<textarea data-constraints="" name="message" placeholder="Message" class="mtext"></textarea>
</label>
</div>
<!--<input class="header_button" type="submit" name="submit" value="Send Request">-->
<div class="header_button">Send Request </div>
<span class="success"><?php echo $successMessage;?></span>
<div class="mfInfo mfProgress"><span class="cnt"></span><span class="loader"></span><span class="msg"></span></div>
</div>
</fieldset>
</form>
</div>
</div>
in the header (which is in included at the index.php start) I added:
<?php require_once "validation.php";?>
because if I put require_once validation.php at the start of the index the form wouldn't be accessed.
in the validation.php this is the part that sends the mail:
if( !($name=='') && !($email=='') && !($phone=='') &&!($message=='') )
{ // Checking valid email.
if (preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$header= $name."<". $email .">";
$headers = "mywebsite.com"; /* Let's prepare the message for the e-mail */
$msg = "Hello! $name Thank you...! For Contacting Us.
Name: $name
E-mail: $email
Phone: $phone
Message: $message
This is a Contact Confirmation mail. We Will contact You as soon as possible.";
$msg1 = " $name Contacted Us. Hereis some information about $name.
Name: $name
E-mail: $email
Phone: $phone
Message: $message "; /* Send the message using mail() function */
if(mail($email, $headers, $msg ) && mail("receiver_mail_id#mywebsite.com", $header, $msg1 ))
{
$successMessage = "Message sent successfully.......";
}
}
else
{
$emailError = "Invalid Email";
}
}
but id doesn't send anything
the page gets reloaded to index.php#
I don't get the invalid email or Message sent successfully messages either
this is the complete validation.php:
<?php // Initialize variables to null.
//echo "validating";
$name =""; // Sender Name
$email =""; // Sender's email ID
$purpose =""; // Subject of mail
$message =""; // Sender's Message
$phone ="";
$nameError ="";
$emailError ="";
$phoneError ="";
$messageError ="";
$successMessage =""; // On submittingform below function will execute.
if(isset($_POST['submit']))
{ // Checking null values in message.
echo "validating2";
if (empty($_POST["name"])){
$nameError = "Name is required";
}
else
{
$name = test_input($_POST["name"]); // check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError = "Only letters and white space allowed";
}
} // Checking null values inthe message.
if (empty($_POST["email"]))
{
$emailError = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
} // Checking null values inmessage.
if (empty($_POST["phone"]))
{
$phoneError = "Phone is required";
}
else
{
$phone = test_input($_POST["phone"]);
} // Checking null values inmessage.
if (empty($_POST["message"]))
{
$messageError = "Message is required";
}
else
{
$message = test_input($_POST["message"]);
} // Checking null values inthe message.
if( !($name=='') && !($email=='') && !($phone=='') &&!($message=='') )
{ // Checking valid email.
if (preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$header= $name."<". $email .">";
$headers = "mywebsite.com"; /* Let's prepare the message for the e-mail */
$msg = "Hello! $name Thank you...! For Contacting Us.
Name: $name
E-mail: $email
Phone: $phone
Message: $message
This is a Contact Confirmation mail. We Will contact You as soon as possible.";
$msg1 = " $name Contacted Us. Here is some information about $name.
Name: $name
E-mail: $email
Phone: $phone
Message: $message "; /* Send the message using mail() function */
if(mail($email, $headers, $msg ) && mail("contact#mywebsite.com", $header, $msg1 ))
{
$successMessage = "Message sent successfully.......";
}
}
else
{
$emailError = "Invalid Email";
}
}
} // Function for filtering input values.function test_input($data)
// Function for filtering input values.
function test_input($data)
{
$data = trim($data);
$data =stripslashes($data);
$data =htmlspecialchars($data);
return $data;
}
?>
any ideas?

send html form with php can't solve

I have big problem with sending easy html form with php.
My problem is when all fields are empty it still send message.
I don't why this code still send empty form??
<form id="form1" name="form1" method="post" action="forma.php">
<p>
<label for="ime">Ime:</label>
<input type="text" name="ime" id="ime" />
</p>
<p>
<label for="prezime">Prezime:</label>
<input type="text" name="prezime" id="prezime" />
</p>
<p>
<label for="email">e-mail:</label>
<input type="text" name="email" id="email" />
</p>
<p>
<label for="poruka">Poruka:</label>
<textarea name="poruka" cols="40" rows="10" id="poruka"></textarea>
</p>
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
My php code:
<?php
if (isset($_POST['submit']))
{
$ime= $_POST['ime'];
$prezime= $_POST['prezime'];
$email= $_POST['email'];
$poruka= $_POST['poruka'];
$email_from = 'neki#email.com';
$email_subject = "forma sa sajta";
$email_body = "Ime: $ime. \n". "Prezime: $prezime \n". "email: $email \n". "poruka: $poruka" ;
$to = "myemail#gmail.com";
mail ($to, $email_subject, $email_body);
echo "Message is sent";
}
else {
echo "Message is not sent";
}
?>
So again, when i fill fields message is sent. It is ok, i received email.
But when i just click submit (without filling fields) it still send message to my email.
What is wrong with this code? I try everything i know, but without success.
Thank you.
The problem is that you are only checking to see if "submit" is set.
Your if statement should read something like:
if(isset($_POST['submit']) && all_other_fields_are_valid($_POST)){...}
function all_other_fields_are_valid($fields)
{
//logic to decide what fields and values you require goes here
}
You need to check all required field. only check submit it will attempt mailing:
if (isset($_POST['submit']
, $_POST['ime']
, $_POST['prezime']
, $_POST['email']
, $_POST['poruka']))
Additionally you can validate from the client side using new HTML5 required attribute:
<input type="text" name="ime" id="ime" required />
This way you don't waste server resources for bad formed requests.
Actually since they are sent as empty variables, they will still evaluate to true in isset(), even if there is no text in the input fields when they are submitted.
if($_POST['ime'] && $_POST['prezime'] && $_POST['email'] && $_POST['poruka']) {
// do stuff here
}
As long as all of these have values and none of the values are 'false' or '0', this will evaluate to true only if somebody puts text in all of the input fields.
This will check if all required POST vars are set, if they're empty and give an error if so:
<?php
if (isset($_POST['submit'], $_POST['ime'], $_POST['prezime'], $_POST['email'], $_POST['poruka']))
{
$error = "";
if($_POST['ime'] == ""){
$error .= "ima was empty!<br />";
}
if($_POST['prezime'] == ""){
$error .= "prezime was empty!<br />";
}
if($_POST['email'] == ""){
$error .= "email was empty!<br />";
}
if($_POST['poruka'] == ""){
$error .= "poruka was empty!<br />";
}
if($error == ""){
$ime= $_POST['ime'];
$prezime= $_POST['prezime'];
$email= $_POST['email'];
$poruka= $_POST['poruka'];
$email_from = 'neki#email.com';
$email_subject = "forma sa sajta";
$email_body = "Ime: $ime. \n". "Prezime: $prezime \n". "email: $email \n". "poruka: $poruka" ;
$to = "myemail#gmail.com";
mail ($to, $email_subject, $email_body);
echo "Message is sent";
} else {
echo $error;
}
} else {
echo "Message is not sent";
}
?>

PHP form takes back to top

I have PHP included a PHP form in my portfolio, that you can see here http://www.tinybigstudio.com The thing is that after SUBMIT, the page goes to TOP instead of staying at the bottom where the form is.
This is the PHP code I have:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#tinybigstudio.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' .$subject = "You have mail, yes!" . "\r\n" . 'Te lo manda: ' . $name;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
And this is the form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<fieldset>
<label for="name">Name</label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required">
<label for="email">Email</label>
<input type="text" size="50" name="email" id="email" value="" class="required">
<label for="message">Message</label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
<input type="submit" value="S E N D" class="send" name="submit" onmouseover="this.className='send_hover';"
onmouseout="this.className='send';">
</form>
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Message Successfully Sent!</strong></p>
<p>Thank you <strong><?php echo $name;?></strong> for sending a message!</p>
<?php }
?>
you need to add an anchor to the contact form and use this as the form action.eg:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>#contact" >
and add this 'pseudo-link' right before the contact form
<a name="contact">Contact me</a>
Now after submit user will be send to the form directly and not the top of the page
This is because you are submitting it to the same page that you are on, therefore the browser goes effectively refreshes with the $_POST data. If you want to stop this you need to use AJAX to submit it so that it happens in the background. Take a look at the API - http://api.jquery.com/jQuery.ajax/

Script should send an email containing form submission values, but no email is getting sent

So I have a HTML form with some PHP but I'm not getting any email whatsoever after submitting it. I can't find the problem! can you help me out?
Tried changing the if(isset($_POST['submit'])) { to 'enviar' but still not working.
tried putting some echos to see where it's not working. the only statement that is stopping at the else statement is stripslashes.
The form snippet:
<div id="contact-wrapper">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you entered valid information.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email sent with success!</strong></p>
<p>Thank you for using our contact form <strong><?php echo $name;?></strong>, we will contact you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
</div>
<div>
<label for="email"><strong>E-mail:</strong></label>
<input type="text" size="50" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="" class="required" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
</div>
<input type="submit" value="enviar" name="submit" id="submit" />
</form>
</div>
and the PHP:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
Before getting any email, you have to be sure the email is being sent.
$sent = mail($emailTo, $subject, $body, $headers);
var_dump($sent);
What does this code output when placed in the appropriate place?
Have you tried a simple php page to do a test Email (eg fixed content) and I assume the webserver has email configured and is prepared to relay for your address?
If this is WordPress contact form, for starters:
mail($emailTo, $subject, $body, $headers);
should be:
wp_mail($emailTo, $subject, $body, $headers);
See: wp_mail codex
Now you have to check your e-mail setup, as well as WordPress e-mail setup too.

Categories