Add validation to PHP form in responsive HTML - javascript

How to I add validation to this php form so that it verifies that a valid email was input and if not post an error message below the input area. I also need it to make sure that all the fields are filled out and that there is no malicious code entered.
Can anyone please help? Thank you in advance.
<?php
$name = $_POST['fullname'];
$email = $_POST['email'];
$message = $_POST['message'];
$subjectCustomer = $_POST['subject'];
$from = 'Contact Form';
$to = 'test#gmail.com';
$subject = "Message from Contact Form: $subjectCustomer";
$location = "http://www.domain.com";
$body = "From: $name\n E-Mail: $email\n Message: $message\n";
## SEND MESSGAE ##
if ($_POST['submit']) {
if ($message != '' && $email != '' && $subject != '') {
if (mail ($to, $subject, $body, $from)) {
echo '<script type="text/javascript">alert("Your message has been sent!"); location.href="index.html";</script>';
} else {
echo '<script type="text/javascript">alert("Something went wrong, go back and try again!"); location.href="index.html/#76industries_contact";</script>';
}
} else {
echo '<script type="text/javascript">alert("You need to fill in all required fields!!"); location.href="index.html/#76industries_contact";</script>';
}
}
?>
<form role="form" method="post" action="contact_form.php" >
<div class="col-md-3">
<div class="form-group">
<input name="fullname" type="text" class="form-control" id="fullname" placeholder="Your Name" maxlength="30">
</div> <!-- end form-group -->
<div class="form-group">
<input name="email" type="text" class="form-control" id="email" placeholder="Your Email" maxlength="30">
</div> <!-- end form-group -->
<div class="form-group">
<input name="subject" type="text" class="form-control" id="subject" placeholder="Your Subject" maxlength="40">
</div> <!-- end form-group -->
<div>
<input id="submit" name="submit" type="submit" value="Send Message" class="btn btn-primary">
</div> <!-- end button -->
</div> <!-- end col-md-3 -->
<div class="form-group">
<div class="col-md-9">
<div class="txtarea">
<textarea name="message" rows="10" class="form-control" id="message" placeholder="Your Message"></textarea>
</div> <!-- end txtarea -->
</div> <!-- end col-md-9 -->
<div> <!-- end form-group -->
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<! Will be used to display an alert to the user>
</div><!-- end col-sm-10 -->
</div> <!-- end form-group -->
</div>
</div>
</form>

here is jquery validation for email and name
$('#submit').click(function(){
var uname=$('#fullname').val();
if($('#fullname').val().match('[a-zA-Z]+\\.?')){
$("#nameerr").css("visibility","hidden");
}
else{
$("#nameerr").text("FullName is InValid" ) ;
$("#nameerr").css("visibility","visible");
return false;
}
});
$('#submit').click(function(){
var email=$('#email').val();
if($('#email').val().match('[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}')){
$("#emailerr").css("visibility","hidden");
}
else
{
$("#emailerr").text("Email Address is InValid.");
$("#emailerr").css("visibility","visible");
return false;
}
});
now you can add another div empty div
<div id="nameerr"> </div>
<div id="emailerr"></div>
now give them css :
#nameerr,#emailerr{
color: red;
background-color:#FFB2B2;
visibility : hidden;
font-weight:bold;
font-size: 12px;
box-shadow: 0 0 5px rgba(255, 0, 0, 1);
width: 150%;
height:10%;
}

As mentioned above in the comments, you can use many ways to achieve what you want.
You could use PHP or JQuery.
If you would like to use PHP, you most likely will end up doing something like:
$name = htmlspecialchars($_POST['fullname']);
$email = $_POST['email'];
$message = htmlspecialchars($_POST['message']);
$subjectCustomer = htmlspecialchars($_POST['subject']);
This takes all the special html characters in a string and converts them to regular html characters.
You can read more on htmlspecialchars here.
Note: You don't want to do a htmlspecialchars() on email addresses. This will convert the # and make it useless.
To check if all fields are filled in, you can use the required attribute from HTML.
Example:
<input name="fullname" type="text" class="form-control" id="fullname" placeholder="Your Name" maxlength="30" required>
Notice that I've placed the attribute inside the input tags.

If you are only looking to achieve client side validation, then I would strongly recommend the jQuery Validation Plugin, that can be found here: http://jqueryvalidation.org/
You can validate your form, on submit with one line of code $("#yourFormName").validate();
Even though you are validating your form's input on the client side, it is still good practice to first check that your variable has some information, then to sanitize your data server side, using a method such as:
if(isset($_POST['fullname'])) {
$name = addslashes($_POST['fullname']
}

Related

Novice developer - Trouble with php contact form templates - probably something dumb

I am a novice developer and for some reason I have never been able to get a php contact form to function properly. I've tried templates from bootstrapious and reusable forms but I've never been able to get them to work. My ultimate goal is to have a form with recaptcha but I can't get just a regular old form to work. Here are the codes from my latest attempt. I've been working on this for days and I feel like I'm missing something small and stupid. Thank you
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact Form Tutorial by Bootstrapious.com</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet" type="text/css">
<link href="custom.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xl-8 offset-xl-2 py-5">
<h1>Contact form Tutorial from Bootstrapious.com</h1>
<p class="lead">This is a demo for our tutorial dedicated to crafting working Bootstrap contact form with PHP and AJAX background.</p>
<p class="lead">This file uses PHPMailer to send the emails.</p>
<form id="contact-form" method="post" action="contact-2.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">Firstname *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Lastname *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please, leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Send message">
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted"><strong>*</strong> These fields are required. Contact form template by Bootstrapious.</p>
</div>
</div>
</div>
</form>
</div><!-- /.8 -->
</div> <!-- /.row-->
</div> <!-- /.container-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js" integrity="sha256-dHf/YjH1A4tewEsKUSmNnV05DDbfGN3g7NMq86xgGh8=" crossorigin="anonymous"></script>
<script src="contact-2.js"></script>
</body>
PHP
<?php
/*
THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
*/
require 'PHPMailer-master/PHPMailerAutoload.php';
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$fromEmail = 'uprightjared#gmail.com';
$fromName = 'Demo contact form';
// an email address that will receive the email with the output of the form
$sendToEmail = 'uprightjared#gmail.com';
$sendToName = 'Demo contact form';
// subject of the email
$subject = 'New message from contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone',
'email' => 'Email', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back
to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try
again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by
error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailTextHtml = "<h1>You have a new message from your contact form</h1>
<hr>";
$emailTextHtml .= "<table>";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
}
}
$emailTextHtml .= "</table><hr>";
$emailTextHtml .= "<p>Have a nice day,<br>Best,<br>Ondrej</p>";
$mail = new PHPMailer;
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName); // you can add more addresses
by simply adding another line with $mail->addAddress();
$mail->addReplyTo($from);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->msgHTML($emailTextHtml); // this will also create a plain-text version
of the HTML email, very handy
if(!$mail->send()) {
throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
// $responseArray = array('type' => 'danger', 'message' => $errorMessage);
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
JS
$(function () {
// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator
$('#contact-form').validator();
// when the form is submitted
$('#contact-form').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "contact-2.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and
apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-
dismissable"><button type="button" class="close" data-dismiss="alert" aria-
hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});

Php File For HTML Php form

I am studying on a site template for quite long. I have a contact form in my site and my html file (index.html) is linked to a js file (contact-me.js). I'm providing them below :
Contact Form In index.html :
<!-- OPEN - Content -->
<div class="item-title text-center">
<!-- Contact form -->
<form id="contact-form" name="contact-form" method="POST" data-name="Contact Form">
<div class="row">
<!-- Full name -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="text" id="name" class="form form-control" placeholder="Write your name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write your name'" name="name" data-name="Name" required>
</div>
</div>
<!-- E-mail -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="email" id="email" class="form form-control" placeholder="Write your email address" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write your email address'" name="email-address" data-name="Email Address" required>
</div>
</div>
<!-- Subject -->
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<input type="text" id="subject" class="form form-control" placeholder="Write the subject" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write the subject'" name="subject" data-name="Subject">
</div>
</div>
<!-- Message -->
<div class="col-xs-12 col-sm-12 col-lg-12 no-padding">
<div class="form-group">
<textarea id="text-area" class="form textarea form-control" placeholder="Your message here... 20 characters Min." onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your message here... 20 characters Min.'" name="message" data-name="Text Area" required></textarea>
</div>
</div>
</div>
<!-- Button submit -->
<button type="submit" id="valid-form" class="btn btn-color">Send my Message</button>
</form>
<!-- /. Contact form -->
<div id="block-answer">
<div id="answer"></div>
</div>
</div> <!-- CLOSE - Content -->
and my contact-me.js is :
$(document).ready(function() {
$("#contact-form [type='submit']").click(function(e) {
e.preventDefault();
// Get input field values of the contact form
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email-address]').val();
var user_subject = $('input[name=subject]').val();
var user_message = $('textarea[name=message]').val();
// Datadata to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userSubject':user_subject, 'userMessage':user_message};
// Ajax post data to server
$.post('php/contact-me.php', post_data, function(response){
// Load json data from server and output message
if(response.type == 'error') {
output = '<div class="error-message"><p>'+response.text+'</p></div>';
} else {
output = '<div class="success-message"><p>'+response.text+'</p></div>';
// After, all the fields are reseted
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$("#answer").hide().html(output).fadeIn();
}, 'json');
});
// Reset and hide all messages on .keyup()
$("#contact-form input, #contact-form textarea").keyup(function() {
$("#answer").fadeOut();
});
});
Can You Please Help Me With The php file. I am completely new to php. Please help me with the php file that I should use for this form.
Here is a sample code.
You need a basic understanding of POST and GET method and read the PHP manual on how to use 'mail()'
<?php
$to = "mail#yourdomain.com";
$from = $_POST['user_email'];
$name = $_POST['user_name'];
$headers = "From: $from";
$subject = $_POST['user_subject'];
$body = $_POST['user_message'];
$send = mail($to, $subject, $body, $headers);
?>
I assumed that you need a php script to send you the data on your mail that user enters
I seriously have no idea why you are using Javascript(you are not verifying data,so use post action method of php. just add action="somename.php" in form tag,somewat like this
<form id="contact-form" name="contact-form" method="POST" action="somename.php">
and in somename.php keep the following content
<?php
$name = $_POST['name'];
$usermail = $_POST['email-address'];
$message = $_POST['message'];
$to = "yourmail#example.com";
$subject = $_POST['subject'];
$text = "Name-" . $name ."\nEmail-" . $usermail ."\nMessage-" . $message;
$headers = "From: webmaster#yourdomain.com" . "\r\n" .
"CC: somebodyelse#example.com";
mail($to,$subject,$text,$headers);
?>
You may continue using javascript(if so dont add action to form tag).

Ajax URL with variable form location

I'm sure the title will get my scoulded by the SO naz. . moderators. But I wasn't sure what to name it.
I have a form that I have saved in it's own php file. I include this form on the bottom of each page on the website. This is the form file.
This should be the minimum needed code to show my issue.
<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){
$name = strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$errors = array();
//Validate input
//Name
if(!empty($name)) {
//Check to see that $name only contains valid characters
if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; }
}else{
$errors[] = "Name field must be filled out.";
}
//End Name
//Phone
if(!empty($phone)) {
}else{
$errors[] = "Phone field must be filled out.";
}
//End Phone
//Email
if(!empty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
}else{
$errors[] = "Email field must be filled out.";
}
//End Email
echo json_encode($errors);
}
?>
<!-- Action Form -->
<section id="sectActionForm">
<div class="row">
<div class="col1 col-md-6">
<img class="noPad" src="/images/banners/karateka.jpg">
</div>
<div id="col2" class="col-md-6 col-xs-12">
<form id="actionForm" class="" role="form" action="index.php" method="POST">
<h3>Get your FREE class today!</h3>
<input id="name" class="form-control" type="text" placeholder="Name" /><br/>
<input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>
<input id="email" class="form-control" type="text" placeholder="Email" />
<input class="btn btn-lg btn-block" type="submit" value="Send" />
</form>
</div>
</div>
</section>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "action.include.php",
dataType: "json",
success: function(data){
alert(data);
}
})
});
</script>
<!-- END Action Form -->
My problem is that since this form could be being accessed from any page, I don't know what to put in the AJAX url section.
My DESIRED BEHAVIOR: I would like for the php errors array to be passed to the ajax so it can be displayed in a modal error box.
not sure if i'm missing something, but you would literally just put the path of the file as the url. So if the name of the form php file is myForm.php, the ajax url would be myForm.php
Try with this...
<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){
$name = strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$errors = array();
//Validate input
//Name
if(!empty($name)) {
//Check to see that $name only contains valid characters
if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; }
}else{
$errors[] = "Name field must be filled out.";
}
//End Name
//Phone
if(!empty($phone)) {
}else{
$errors[] = "Phone field must be filled out.";
}
//End Phone
//Email
if(!empty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
}else{
$errors[] = "Email field must be filled out.";
}
//End Email
exit(json_encode($errors)); // exit so it doesn't send the form below
}
?>
<!-- Action Form -->
<section id="sectActionForm">
<div class="row">
<div class="col1 col-md-6">
<img class="noPad" src="/images/banners/karateka.jpg">
</div>
<div id="col2" class="col-md-6 col-xs-12">
<form id="actionForm" class="" role="form" action="index.php" method="POST">
<h3>Get your FREE class today!</h3>
<input id="name" class="form-control" type="text" placeholder="Name" /><br/>
<input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>
<input id="email" class="form-control" type="text" placeholder="Email" />
<input class="btn btn-lg btn-block" type="submit" value="Send" />
</form>
</div>
</div>
</section>
<script type="text/javascript">
$("#actionForm").on('submit', function(event){
event.preventDefault(); // so it doesnt reload the page
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'] ?>",
dataType: "json",
success: function(data){
alert(data);
}
});
});
</script>
<!-- END Action Form -->
Where are the 'name' attributes? All I see is 'id' and $_POST submits the name and value. Did this code ever work? What am I missing?
EDIT:
Place this line of code right above your <form>: <h4 id="errors" class="error"><?php if(isset($errors) && count($errors)) echo($errors);?></h4>. Add a class called 'error' and style it the way you want. You might want to add a <br> tag to the end of each error message. Or use the explode command instead of adding the <br> tag and the echo command.

Contact Form mailer.php returns a blank page

The contact form was working fine until I tried to add reCAPTCHA. I have managed to make reCAPTCHA appear, have the recaptchalib , and the mailer.php which is the page displaying a blank page. Any ideas what I am doing wrong?
Here is the mailer.php
<?php
if(isset($_POST['submit'])) {
// check reCAPTCHA information
require_once('recaptchalib.php');
$privatekey = "privatekey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
// if CAPTCHA is correctly entered!
if ($resp->is_valid) {
// great success!
$myemail = "operations#socialmarketing.com";
/* Check all form inputs using check_input function */
$name = $_POST['inputName'];
$email = $_POST['inputEmail'];
$subject = $_POST['inputSubject'];
$message = $_POST['inputMessage'];
/* Let's prepare the message for the e-mail */
$subject = "Message From LGBT campaign Contact Form";
$message = "
China LGBT Contact Form
Name: $name
Email: $email
Message:
$message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location: successPage.html#contact');
} else {
// alert the captcha is not correct
}
}?>
Here is my HTML page, which I have made a .php page
<div class="marketing">
<div class="intro" id="contact">
<h1>Contact Us</h1>
<p>If you would like to stay informed about our progress or would like to help with the campaign, please fill out this form to send us an email.</p>
<div class="panel-body">
<form name="contactform" id="contactform" action="mailer.php" class="form-horizontal" role="form" method="POST">
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="inputName" placeholder="Your Name">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="email" class="form-control" name="inputEmail" placeholder="Your Email">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea class="form-control" rows="4" name="inputMessage" placeholder="Your message..."></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<p>Prove you are not a spambot</p>
<?php require_once('recaptchalib.php');
$publickey = "publickey";
echo recaptcha_get_html($publickey);
?>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-primary">Send Message</button>
</div>
</div>
</form>
</div>
</div>
Any help with this would be hugely appreciated guys.
Thanks a bunch
SOLUTION
<form name="contactform" id="contactform" action="mailer.php" class="form-horizontal" role="form" method="post">
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="inputName" placeholder="Your Name">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="email" class="form-control" name="inputEmail" placeholder="Your Email">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea class="form-control" rows="4" name="inputMessage" placeholder="Your message..."></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<p>Prove you are not a spambot</p>
<?php require_once('recaptchalib.php');
$publickey = "6Le0ff0SAAAAAOCeQiOcGUwQEfXERDyNJ";
echo recaptcha_get_html($publickey);
?>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<input type="submit" class="btn btn-primary" value="Send Message" name="submit">
</div>
</div>
</form>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['submit'])) {
// check reCAPTCHA information
require_once('recaptchalib.php');
$privatekey = "6Le0ff0SAAAALTDn4IkqNSN5F0AU2Ezhvf";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
// if CAPTCHA is correctly entered!
if ($resp->is_valid) {
// great success!
$myemail = "kenm#socialmarketing.com";
/* Check all form inputs using check_input function */
$name = $_POST['inputName'];
$email = $_POST['inputEmail'];
$subject = "Message From LGBT campaign Contact Form";
$message = $_POST['inputMessage'];
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
/* Let's prepare the message for the e-mail */
$message = "
China LGBT Contact Form
Name: $name
Email: $email
Message:
$message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location: successPage.html#contact');
} else {
// alert the captcha is not correct
echo "captcha did not match!";
exit;
}
}?>
Change your button to this:
<input type="submit" class="btn btn-primary" value="Send Message" name="submit">
POST is looking for a named attribute called submit.
which based on your conditional statement, and nothing will execute inside it because of it:
if(isset($_POST['submit'])) {...}
You also don't have a named form element to go with $subject = $_POST['inputSubject'];
Either add one:
Subject:<input type="text" class="form-control" name="inputSubject" placeholder="Subject">
or simply test with:
$subject = "Form submitted";
You should make sure that all fields are filled. If the subject is left empty or any other, you may not receive mail because of it, especially the Email field.
Another reason may be because you do not have proper headers, including a From:
Visit the PHP.net website on mail:
http://php.net/manual/en/function.mail.php
Example From: header from the website:
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
and modifying mail($myemail, $subject, $message);
to mail($myemail, $subject, $message, $headers);
Quoting them:
Note:
When sending mail, the mail must contain a From header. This can be set with the additional_headers parameter, or a default can be set in php.ini.
Failing to do this will result in an error message similar to Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing. The From header sets also Return-Path under Windows.
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.
If you're getting a blank page, it's because something is failing and not showing an error. I'd start by making sure that error reporting is enabled in your PHP script. Add this to the top of mailer.php.
ini_set('display_errors',1);
error_reporting(E_ALL);
You also need to add some sort of message here.
} else {
// alert the captcha is not correct
echo "captcha did not match!";
exit;
}
Also as mentioned, check your error log.
You can start by changing
<button type="submit" class="btn btn-primary">Send Message</button>
to
<input type="submit" class="btn btn-primary" value="submit">
This should submit your form to mailer.php. From that point on it should work.

How to return to the previous page after a submit form with php?

I have a form in html whose "action" attribute calls a contact.php file. The problem is that after I submit the form, the file that is visible is a blank page with the address contact.php and I want to see again the form of the main page.
HTML:
<form id="myForm" action="php-contact/contact.php"
method="post" class="contact_form" autocomplete="off"
role="form">
<div class="form-group">
<label for="input-subject">subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="your subject" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-name">name</label>
<input name="name" type="text" class="form-control" id="name" placeholder="your name" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-email">email address</label>
<input name="email" type="text" class="form-control" id="email" placeholder="your email" maxlength="40"/>
</div>
<div class="form-group" >
<label for="input-message">message</label>
<textarea name="message" cols="10" rows="10" class="form-control" id="comment" ></textarea>
</div>
<button name="myFormSubmitted" type="submit" class="btn btn-primary btn-lg btn-block">send</button>
</form>
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "pep.g#gmail.com";
$message = '
name: '.$name.'
email: '.$email.'
message: '.$message.'
';
$headers = 'From: pep.website#website.com';
if (
mail($to, $subject, $message, $headers)
)
echo"<script>alert('message send succesfully')</script>";
else
echo"<script>alert('message not send')</script>";
?>
Use either $_SERVER["HTTP_REFERER"] or use a hidden field on the form with the url of the current page:
<form action="myAction.php">
<input type="hidden" name="destination" value="<?php echo $_SERVER["REQUEST_URI"]; ?>"/>
<!-- other form inputs -->
<input type="submit"/>
</form>
myAction.php
<?php
/* Do work */
if(isset($_REQUEST["destination"])){
header("Location: {$_REQUEST["destination"]}");
}else if(isset($_SERVER["HTTP_REFERER"])){
header("Location: {$_SERVER["HTTP_REFERER"]}");
}else{
/* some fallback, maybe redirect to index.php */
}
And then even then you should have fallbacks in case for some reason the client isn't respecting HTTP redirects, like some redirect javascript, a meta redirect and a link to the destination.
Add a JS redirect after your alert then
echo "<script>
alert('message sent succesfully');
window.history.go(-1);
</script>";
In your contact.php file, just use something like at the end of the PHP code:
header("location:yourfilenamehere.php");
This will redirect back to whatever page you specify.
You could do two things...
1) Have your php logic in the form file and submit to that file. On the top of the file, put something like:
if(isset($_POST['name'])) {
// your sending logic
}
followed by your form.
2) use the header() function to redirect to your form.
header("Location: form.html");
I feel pretty bad about posting this answer as it is just concatenating two other SO answers.
First part
Charlie74's answer on this page
// add the message you want to show to the user
header("Location: yourfilenamehere.php?alertmsg=message+send+succesfully");
exit();
Second part check for the alertmsg name in the query string
See SO post for getParameterByName:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
in the page you are redirecting call the getParameterByName function:
<script>
var msg = getParameterByName('alertmsg');
if (alertmsg.length > 0) {
alert(msg);
}
</script>

Categories

Resources