PHP and Javascript Validation of Password Match - javascript

Trying to get page to dynamically show if passwords match (echo 'Match' or 'Do not match'). (Similiar to previous question asked here.)
Looking to check if password1 and password2 are the same as you type in either the 'password' or 'confirm password' input boxes.
EDIT: Seems elseif ($password2 == $password1) isn't checking for the match as I intended. Posting of password1 and password2 works (#feedback changes to 'Do not match' as you type in either input box, but 'Match' never shows). Any help on how to fix this code is appreciated.
check.php
<?php
include __DIR__ . '/mysqli_connect.php';
$password2 = mysqli_real_escape_string($dbc, $_POST['password2']);
$password1 = mysqli_real_escape_string($dbc, $_POST['password1']);
if ($password2==NULL && $password1==NULL) {
echo '';
} elseif ($password2 == $password1) {
echo 'Match';
} else {
echo 'Do not match';
}
register.php
<script type="text/javascript" src="/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function() {
$('#feedback').load('/includes/check.php').show();
$('#password1').keyup(function() {
$.post('/includes/check.php', { password1: form.password1.value },
function(result) {
$('#feedback').html(result).show;
});
});
});
$(document).ready(function() {
$('#feedback').load('/includes/check.php').show();
$('#password2').keyup(function() {
$.post('/includes/check.php', { password2: form.password2.value },
function(result) {
$('#feedback').html(result).show;
});
});
});
</script>
<form action="register.php" method="post" name="form">
<input id="password1" class="signup_input_box" type="password" name="password1" maxlength="20" value="<?php if (isset($trimmed['password1'])) echo $trimmed['password1']; ?>">
<input id="password2" class="signup_input_box" type="password" name="password2" maxlength="20" value="<?php if (isset($trimmed['password2'])) echo $trimmed['password2']; ?>">
<div id="feedback"></div>
<p><center><input type="submit" name="submit" value="Register"></center>
</form>

Skipped using MySql posting and used JS only to check the value of the password inputs and show text upon keyup. Reference here.

Related

PHP,jQuery,HTML form with ajax is not working

I'm trying to submit form data to php script with jQuery .post() method,than to receive php script data back and display it on form page,but it doesnt work.Also I'm using jQuery validate plugin for client side validation as well.Here is my code:
Html:
<div class="contact-form">
<button class="contact-close">X</button>
<form method="post" action="formular.php" id="quote-form">
<div id="returned"></div>
<div class="houndred">
<input type="text" name="name" placeholder="Name*" class="input-half" id="name" min-width="2" autofocus required>
<input type="email" name="email" placeholder="Email*" class="input-half" id="email" required>
<input type="text" name="subject" placeholder="Subject" class="input-half" id="subject" required>
<input type="url" name="url" placeholder="Website" class="input-half" id="website">
</div>
<div class="houndred">
<textarea name="message" class="textarea" id="message" placeholder="message*" required></textarea>
<br><p></p>
</div>
<div class="eightytwo">
<button id="quote-button">Send</button>
</div>
<div id="summary"></div>
</form>
</div><!-- .padding-fix -->
<script src="js/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="js/validation.js"></script>
<script src="js/ajaxform.js"></script>
JS for posting:
$(document).ready(function(){
$('form').on('submit', function(event) {
event.preventDefault();
$.post('formular.php', $(this).serialize(), function(data)) {
var dataForm = data;
$("#returned").append(dataForm);
}
});
)};
and PHP:
if(!empty($_POST)) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$url = $_POST['url'];
$message = $_POST['message'];
if(empty($name) || empty($email) || empty($subject) || empty($url) || empty($message)) {
$errors[] = 'All fields are required!';
} else {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter a valid email address';
}
if(ctype_alpha($name === false)) {
$errors[] = 'Name can only contain letters';
}
if (ctype_alpha($subject === false)) {
$errors[] = 'Subject can only contain letters';
}
if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED) === false) {
$errors[] = 'Please enter a valid url address with http in front';
}
if(empty($message)) {
$errors[] = 'Please enter a message';
}
}
if(!empty($errors)) {
echo '<ul style=\"list-style: circle; color: #f74d4e\">';
foreach($errors as $error) {
echo '<li style=\"color: #f74d4e;\"' . $error . '</li>';
}
echo '</ul>';
}
$send_message = 'From:' . $url . '<br>' . strip_tags(addslashes($message));
if(empty($errors)) {
mail('something#something.com', $subject, $send_message , $email);
echo '<h4 style=\"color: #f74d4e;\">Thank you for contacting me!</h4>';
exit();
}
}
I'm hoping that this makes sense,to me it had,but I'm strugling with it for last couple of hours,still trying to figure out what went wrong,I also tryed posting with $.ajax() and no response.One more thing,form is geting loaded using jquery .load() method to popup box,that is why it is important to me to do it with ajax
From a cursory inspection of your code, it seems that you have added an extra closing parentheses in this line, like so: function(data))
$.post('formular.php', $(this).serialize(), function(data)) {
try
$.post('formular.php', $(this).serialize(), function(data) {
instead
HTH

Ajax Form Not Doing Anything

I have a form using Ajax that is suppose to show an error to the user when something is incorrect when the login. When I click the submit button nothing happens. I hate asking Stack overflow but you got to do what you got to do. And yes, I have Apache configured to not need file extensions.
This is the tutorial I am following: https://www.youtube.com/watch?v=L7Sn-f36TGM
Login Script:
require("dbh.php");
if(isset($_POST['submit'])) {
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$errorEmpty = false;
$errorEmail = false;
$errorWrong = false;
if(empty($email) || empty($pwd)) {
echo "<p class='loginText'>Please Enter an Email Address and Password!</p>";
$errorEmpty = true;
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<p class='loginText'>Please Enter a Valid Email Address!</p>";
$errorEmail = true;
} else {
echo "Success!";
}
} else {
echo "<p class='loginText'>An Error Occurred!</p>"
}
header("/login?test");
loginForm.js
$(document).ready(function() {
$("#loginFormInput").submit(function(event) {
event.preventDefault();
var email = $("#emailLogin").val();
var pwd = $("#pwdLogin").val();
$(".errorText").load("../php-scripts/login", {
email: email,
pwd: pwd
});
});
});
HTML Form:
<p class="errorText"></p>
<form action="../php-scripts/login.php" method="post" id="loginFormInput">
<input type="text" name="email" class="textInput" id="emailLogin" placeholder="Email" maxlength="512"> <br>
<input type="password" name="pwd" class="textInput" id="pwdLogin" placeholder="Password" maxlength="1024"> <br>
<p class="rememberText">Remember Me:</p>
<input type="checkbox" name="remember" class="rememberBox"> <br>
<input type="submit" value="Login" name="submit" class="submitInput" title="Login">
</form>
Your PHP code is doing if (isset($_POST['submit'])), but when you do the AJAX submission you don't provide a submit parameter. You need to add that to the parameters:
$(".errorText").load("../php-scripts/login", {
email: email,
pwd: pwd,
submit: 'Login'
});
Or you could remove that check from the PHP, if that script is only used to process the AJAX requests.
I think you're missing an element with class name errorText
Try adding a <div class="errorText"></div> somewhere

Displaying form confirmation message on form submit

Thought you might be able to help with this, as I sort of know what I want and how to do it but I am not overally familiar with AJAX/JS and after a certain point I just stopped taking stuff in.
Basically, I am trying to have some text appear when a user submits a form, but obviously only when the form is successfully sent. My HTMl and PHP are below, but I have no idea what I am doing beyond this point so maybe someone can give me a little hand.
<form name="contactform" action="includes/contactprocess.php" method="post">
<div class="form-group">
<input type="text" class="form-control" id="fname" name="fname" required placeholder="First Name">
</div>
<div class="form-group">
<input type="text" class="form-control" id="sname" name="sname" required placeholder="Last Name">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" required placeholder="Email Address">
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" required placeholder="Message Subject">
</div>
<div class="form-group">
<textarea rows="3" name="comment" class="form-control" required placeholder="Enter Comment"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Here is the PHP thus far:
<?php
/* Set e-mail recipient */
$myemail = "myemailhere";
/* Check all form inputs using check_input function */
$fname = check_input($_POST['fname'], "Enter your first name");
$sname = check_input($_POST['sname'], "Enter your second name");
$subject = check_input($_POST['subject'], "Enter the message subject");
$email = check_input($_POST['email']);
$comment = check_input($_POST['comment'], "Enter the message you wish to be sent");
/* Error handling and sanitisation for email */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("The e-mail you have entered is not valid");
}
/* Let's prepare the message for the e-mail */
$message = "A contact form has been submitted by;
Name: $fname
Surname: $sname
E-mail: $email
Comments:
$comment
Message sent via myemailhere
";
/* Send message via mail function */
mail($myemail, $subject, $message);
if(mail($myemail, $subject, $message)) {
$data['success'] = true;
}
else{
$data['success'] = false;
}
// convert the $data to json and echo it
// so jQuery can grab it and understand what happend
echo json_encode($data);
/* Check input */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
The JS/AJAX I don't really understand:
<script>
$(document).ready(function() {
// hide the success message
$('#success').hide();
// process the form
$('form').submit(function(event) {
// get the form data before sending via ajax
var formData = {
'name' : $('input[name=name]').val(),
'number' : $('input[name=number]').val(),
'message' : $('input[name=message]').val(),
'contactSubmit' : 1
};
// send the form to your PHP file (using ajax, no page reload!!)
$.ajax({
type: 'POST',
url: 'file.php', // <<<< ------- complete with your php filename (watch paths!)
data: formData, // the form data
dataType: 'json', // how data will be returned from php
encode: true
})
// JS (jQuery) will do the ajax job and we "will wait that promise be DONE"
// only after that, we´ll continue
.done(function(data) {
if(data.success === true) {
// show the message!!!
$('#success').show();
}
else{
// ups, something went wrong ...
alert('Ups!, this is embarrasing, try again please!');
}
});
// this is a trick, to avoid the form submit as normal behaviour
event.preventDefault();
});
});
</script>

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.

AJAX script alerts for contact form with PHP, Google reCAPTCHA, and SweetAlert

I am using an AJAX script to submit a basic contact form at the bottom of my HTML that uses Google reCAPTCHA. The html code is:
<div class="col-md-6">
<form role="form" id="form" action="form.php" method="post">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name">
<span class="help-block" style="display: none;">Please enter your name.</span>
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
<label for="exampleInputText1">Message</label>
<textarea class="form-control" rows="3" id="message" name="message" placeholder="Enter message"></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="I HAVE REMOVED MY SITE KEY"></div>
<span class="help-block" style="display: none;">Please check that you are not a robot.</span>
</div>
<button type="submit" id="Submit" data-loading-text="Sending..." class="btn btn-default">Submit</button>
</form>
</div>
<!-- Placed at the end of the document so the pages load faster -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="slick/slick.min.js"></script>
<script src="assets/js/smoothscroll.js"></script>
<script src="assets/js/jquery.stellar.min.js"></script>
<script src="assets/js/fancybox/jquery.fancybox.js"></script>
<script src="assets/js/main.js"></script>
<script src="alert/sweetalert2.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
I have created a very basic php to email me the data entered into the form.
<?php
//include CSS Style Sheet
echo "<link rel='stylesheet' type='text/css' href='alert/sweetalert2.css' />";
//include a javascript file
echo "<script type='text/javascript' src='alert/sweetalert2.min.js'></script>";
// Define some constants
define( "RECIPIENT_NAME", "Paul O'Shea" );
define( "RECIPIENT_EMAIL", "I HAVE REMOVED MY EMAIL" );
define( "EMAIL_SUBJECT", "Website Enquiry" );
$full_name;$email;$subject;$message;$captcha;
if(isset($_POST['name'])){
$name=$_POST['name'];
}if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['message'])){
$message=$_POST['message'];
}if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("ERROR!","In order to avoid SPAM mail, you must confirm you are human. Please select IM NOT A ROBOT and complete the simple challenge","error");';
echo '}, 1000); </script>';
exit;
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?I HAVE REMOVED MY SECRET KEYresponse=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo "<script type=\"text/javascript\">alert('Message Failed. Please try again'); location.href='index.html#contact';</script>";
}else
{
// If all values exist, send the email
if ( $name && $email && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $name . " <" . $email . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}
echo "<script type=\"text/javascript\">alert('Thanks for your enquiry! Your message has been sent to Paul and he will be in touch within 48hrs'); location.href='index.html#contact';</script>";
}
?>
The PHP has 3 alerts within it:
reCAPTCHA has not been run.
If reCAPTCHA fails.
Success message.
These PHP alerts work if i bypass the AJAX script, (however open a blank form.php) but don't work at all when I use the AJAX script. Therefore I get a success alert from the AJAX script - even if the reCAPTCHA has not been completed - and the form data has not been emailed.
This is my AJAX script:
<script type="text/javascript">
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
swal(
'Thanks for your enquiry!',
'Your message has been sent. Paul will be in contact soon.',
'success'
);
}
});
ev.preventDefault();
});
</script>
This gives the desired result, the email is sent, and the nice alert is shown over the original page, and when closed returns to original page. However, none of the alerts referenced in form.PHP are displayed. If user forgets to run reCaptcha - the same success alert is shown - even though there message will not be emailed.
Can anyone help me add the PHP alerts to the AJAX javascript? I tried copy and paste the same code - but am a little unsure of the appropriate way to format the code. Any help greatly appreciated! Thanks!
I would remove the <script> responses from your php script and instead use plain text, then I'd go with an AJAX approach of form submission.
There are plenty of examples using this (recommended in my opinion) approach, check the following two:
Using just jQuery: jQuery Ajax POST example with PHP
jQuery AJAX submit form
Another approach is to create one file with both your HTML and php in it,
and don't redirect your form post to another page but to itself.
However, this would invoke a page refresh.
Check the following example:
Refresh page after form submitting - Check 1st Answer
Keywords for further searching: post form, ajax, php, jquery, jquery form plugin malsup
EDIT 1 - Code
HTML/JS:
<div class="col-md-6">
<form role="form" id="form" action="form.php" method="post">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name">
<span class="help-block" style="display: none;">Please enter your name.</span>
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
<label for="exampleInputText1">Message</label>
<textarea class="form-control" rows="3" id="message" name="message" placeholder="Enter message"></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="I HAVE REMOVED MY SITE KEY"></div>
<span class="help-block" style="display: none;">Please check that you are not a robot.</span>
</div>
<button type="submit" id="Submit" data-loading-text="Sending..." class="btn btn-default">Submit</button>
</form>
</div>
<!-- Placed at the end of the document so the pages load faster -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="slick/slick.min.js"></script>
<script src="assets/js/smoothscroll.js"></script>
<script src="assets/js/jquery.stellar.min.js"></script>
<script src="assets/js/fancybox/jquery.fancybox.js"></script>
<script src="assets/js/main.js"></script>
<script src="alert/sweetalert2.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
$(document).ready(function(e) {
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if (data == "error")
{
swal("ERROR!","In order to avoid SPAM mail, you must confirm you are human. Please select IM NOT A ROBOT and complete the simple challenge","error");
}
else if (data == "fail")
{
swal("Failed", "Message Failed. Please try again!", "error");
location.href='index.html#contact';
}
else if (data == "success")
{
swal("Thanks for your enquiry!", "Your message has been sent to Paul and he will be in touch within 48hrs", "success");
location.href='index.html#contact';
}
else
{
swal("Something went wrong!", data, "error");
}
}
});
ev.preventDefault();
});
});
</script>
Your php script:
<?php
// Define some constants
define( "RECIPIENT_NAME", "Paul O'Shea" );
define( "RECIPIENT_EMAIL", "I HAVE REMOVED MY EMAIL" );
define( "EMAIL_SUBJECT", "Website Enquiry" );
$full_name;$email;$subject;$message;$captcha;
if(isset($_POST['name']))
{
$name=$_POST['name'];
if($name != filter_var($name, FILTER_SANITIZE_STRING))
{
echo "Name is not valid!";
exit(); // or exit w/e you please
}
}
else
{
echo "Name field is required!";
exit(); // or exit w/e you please
}
if(isset($_POST['email']))
{
$email=$_POST['email'];
if(! filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "Email is not valid!";
exit(); // or exit w/e you please
}
}
else
{
echo "Email field is required!";
exit(); // or exit w/e you please
}
if(isset($_POST['message']))
{
$message=$_POST['message'];
if($message != filter_var($message, FILTER_SANITIZE_STRING))
{
echo "Name is not valid!";
exit(); // or exit w/e you please
}
}
else
{
echo "Message field is required!";
exit(); // or exit w/e you please
}
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha)
{
echo 'error';
exit();
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?I HAVE REMOVED MY SECRET KEYresponse=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo 'fail';
// No need to exit() here, code ends after this anyway
}
else
{
// If all values exist, send the email
if ( $name && $email && $message )
{
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $name . " <" . $email . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
echo "success";
}
else
{
echo "Name, email and message are required!";
}
// No need to exit() here, code ends after this anyway
}
?>
EDIT 2 - Validation (Added in code as well)
You can use php's filter_var function with the available filters
to validate your input. Likewise, if a validation fails you can echo and exit accordingly with a message like echo 'other' which would invoke the last if case at the JS above (just fix the title perhaps to something like "Input error" or "Invalid input").

Categories

Resources