How to make google ReCAPTCHA required in php - php

I have one PHP form with some fields and google ReCAPTCHA field and values store in the database table, But i want to make the google ReCAPTCHA field required.
Code here:
<?PHP
if(isset($_POST['submit']))
{
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
$user_id=$_SESSION['id'];
$sql="insert into contact (name,email,message,user_id,status)
values('$name','$email','$message','$user_id','1')";
$qex=mysql_query($sql);
if(!$qex)
{
die("Contact information is not Added".mysql_error());
}
$msgsec="Contact information is Added";
?>
form code:
<script src='https://www.google.com/recaptcha/api.js'></script>
<form id='contactus' method='post' >
<input type='hidden' name='submit' id='submit' value='1'/>
<label><h2>Your Name <strong style="color:red">*</strong></h2></label>
<input type="text" class="form-control" required name="name" id="name" placeholder="Please enter you'r name"/>
<label><h2>Your Email <strong style="color:red">*</strong></h2></label>
<input type="email" class="form-control" required name="email" id="email" placeholder="Please enter you'r email address"/>
<label><h2>Your Message <strong style="color:red">*</strong></h2></label>
<textarea class="form-control" required name="message" id="message" placeholder="Please type you'r message here"></textarea>
<br />
<div class='container'>
<div class="g-recaptcha" data-sitekey="6LevWB0UAAAAAEPIUh40HptW3PxfYFqjvz2Wa05D"></div>
</div>
<div class='container'>
<input type="submit" name="submit" class="btn btn-primary" value="SEND MESSAGE">
</div>
</form>
as of now the Google ReCAPTCHA option is not required. the form details always stored with submit button wheather i click on captcha or not. i want to make Google ReCAPTCHA required. please check my code and let me know. what i am missing.
Thanks and Regards.
Ankit

Here is google captcha with validation
<html>
<script src='https://www.google.com/recaptcha/api.js'></script>
<?PHP
/*Site Key and secret key is different thing so change it with ur keys */
$errMsg ="";
if(isset($_POST['submit']))
{
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
//your site secret key
$secret = '*********************';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
print_r($responseData);
$name = !empty($_POST['name'])?$_POST['name']:'';
$email = !empty($_POST['email'])?$_POST['email']:'';
$message = !empty($_POST['message'])?$_POST['message']:'';
$user_id=$_SESSION['id'];
if($responseData->success):
//contact form submission code
$sql="insert into contact (name,email,message,user_id,status)
values('$name','$email','$message','$user_id','1')";
$qex=mysql_query($sql);
if(!$qex)
{
die("Contact information is not Added".mysql_error());
}
$errMsg="Contact information is Added";
else:
$errMsg = 'Robot verification failed, please try again.';
endif;
else:
$errMsg = 'Please click on the reCAPTCHA box.';
endif;
}
echo $errMsg ;
?>
<body>
<form id='contactus' method='post' >
<input type='hidden' name='submit' id='submit' value='1'/>
<label><h2>Your Name <strong style="color:red">*</strong></h2></label>
<input type="text" class="form-control" required name="name" id="name" placeholder="Please enter you'r name"/>
<label><h2>Your Email <strong style="color:red">*</strong></h2></label>
<input type="email" class="form-control" required name="email" id="email" placeholder="Please enter you'r email address"/>
<label><h2>Your Message <strong style="color:red">*</strong></h2></label>
<textarea class="form-control" required name="message" id="message" placeholder="Please type you'r message here"></textarea>
<br />
<div class='container'>
<div class="g-recaptcha" data-sitekey="*********************"></div>
</div>
<div class='container'>
<input type="submit" name="submit" class="btn btn-primary" value="SEND MESSAGE">
</div>
</form>
</body>
</html>

in your php file add this
if(isset($_POST['submit']))
{
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
$user_id=$_SESSION['id'];
$sql="insert into contact (name,email,message,user_id,status)
values('$name','$email','$message','$user_id','1')";
$qex=mysql_query($sql);
if(!$qex)
{
die("Contact information is not Added".mysql_error());
}
$msgsec="Contact information is Added";
}
else
{
//your message for select recaptcha or required
}
}

Related

PHP - Problem on validating empty form field

I have a simple form that contains three inputs: name, message and email.
On the server side, I validate all these fields, however, I'm strugling to validate the name field. If I leave the input blank or start writing with a space (single, double, or more) and hit on submit, my php code is accepting this name as valid (where it should not).
Does someone knows how to prevent this? 
Heres my code:
Page 1 - the form:
<form action="enviar-email.php" method="POST" name="emailform">
<div class="form-group">
<input type="text" class="form-control" id="name" name="nome" placeholder="Type your name here" >
</div>
<div class="form-group">
< input type="text" class="form-control" id="email" name="email" placeholder="Youre#email.com here">
</div>
<div class="form-group">
<textarea class="form-control" cols="30" rows="10" maxlength="300" id="message" name="mensagem" placeholder="write your message" ></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Send" class="btn btn btn-special" onclick="alert('Thanks!')" >
</div>
</form>
Page 2 - PHP page where I validate the fields.
if(isset($_POST['nome'])){ $nome = $_POST['nome']; }
if(isset($_POST['email'])){ $email = $_POST['email']; }
if(isset($_POST['mensagem'])){ $message = $_POST['mensagem']; }
// blank fields or name that start with space are not getting caught by this if
if(isset($nome) && trim($nome) !== ""){
Header("location:contato.php");
}
if (!preg_match("/^[a-zA-Z ]+$/",$nome)) {
Header("location:contato.php");
}
you can try like this -
if(isset($_POST['name']) && !empty($_POST['name'])){ $name = $_POST['name']; }

Call php validation file with ajax call

I am trying to submit a form using Ajax, the problem is the validation file I made is not called at all (I checked it by putting a bit of js alert inside the PHP validation file). I searched the internet and tried a lot of solutions but none worked. Is there something wrong I am making in my code?
Here is my HTML:
<form method="post" id="signup">
<div class="form-group">
<input type="fname" name="fname" id="fname" value="" class="form-control" placeholder="Your First name" />
</div>
<div class="form-group">
<input type="lname" name="lname" id="lname" value="" class="form-control" placeholder="Your Last name" />
</div>
<div class="form-group">
<input type="email" name="email" id="email" value="" class="form-control" placeholder="Your Email" />
</div>
<div class="form-group">
<input type="password" name="password" id="password" value="" class="form-control" placeholder="Your Password" />
</div>
<div class="form-group submit-btn">
<input id="signupsumbit" type="submit" name="submit" value="Sign Up" class="btn btn-success btn-lg"/>
</div>
</form>
And here is the ajax call:
$(function (){
$('#signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: $('#signup').serialize(),
url: 'login.php',
success: function (data) {
alert("data is"+data);
}
});
});
});
Here is a bit of my PHP code:
include("connection.php");
echo "<script>alert(2)</script>";
if (isset($_GET['logout']) and $_GET['logout']==1 and isset($_COOKIE[id]))
{
setcookie("email", '', time()-60*60*24);
setcookie("password", '', time()-60*60*24);
setcookie("id", '', time()-60*60*24);
$message = "You have been logged out! Come back soon!";
}
if(mysqli_connect_error()) // if failed to connect to database
{
die("Could not connect to database"); //stop the whole script from runnning
}
if (isset($_POST['submit']) and $_POST['submit'] == 'Sign Up')
{
echo '<script>console.log(1)</script>'; //
$error = '';
$success = '';
// email validation
$email = $_POST['email'];
if (empty($_POST['email']))
{
$error .="<br />Please enter your email";
}
else
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .="<br />Please enter a valid email address";
}
}
.
.
.
.
?>
And of course, the PHP file I made validation at is called login.php.
As you may notice, I put two alerts in my PHP code, I alerted 2 to make sure that the file is called, and alerted 1 to make sure that the form was posted. Odds are, when I submit the form the normal way (with no AJAX), both of alerts work, but when I submit it with AJAX, none of them is alerted.
My Console shows this:
Any help would be appreciated. Thanks.
Testing your script, i found that the submit button is not sent to your login.php script. If you e.preventDefault() and then later trigger the submit, javascript was submitting the form but not the button. To fix your issue create a hidden field with name submit and value Sign Up and remove the name attribute from your submit button (don't need that) and it should work fine.
<form method="post" id="signup">
<input type="hidden" name="submit" value="Sign Up"> <!-- note this hidden field -->
<div class="form-group">
<input type="fname" name="fname" id="fname" value="" class="form-control" placeholder="Your First name" />
</div>
<div class="form-group">
<input type="lname" name="lname" id="lname" value="" class="form-control" placeholder="Your Last name" />
</div>
<div class="form-group">
<input type="email" name="email" id="email" value="" class="form-control" placeholder="Your Email" />
</div>
<div class="form-group">
<input type="password" name="password" id="password" value="" class="form-control" placeholder="Your Password" />
</div>
<div class="form-group submit-btn">
<input id="signupsumbit" type="submit" value="Sign Up" class="btn btn-success btn-lg"/><!-- note the removed name attribute -->
</div>
</form>

How to validate picture captcha..?

Here i have tried out giving user a picture captcha using google api..But the problem is even if user click on submit even without submitting captcha user is registered..!!
here gose .html file
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required="">
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required="">
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required="">
</div>
<div class="form-group" id="recaptcha_widget">
<div class="required">
<div class="g-recaptcha" data-sitekey="6Lc4vP4SAAAAABjhRjyoMguw66mNSBgdpBF398AG"></div>
<!-- End Thumbnail-->
</div>
<?php include("js/captcha.php");?>
</div>
<div class="form-group">
<div cle the terms and policy </label></div>
</div>ass="checkbox i-checks"><label> <input type="checkbox"><i></i> Agre
<button type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b">Register</button>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
</form>
And here gose the .php file
<?php
if(isset($_POST['submit'])){
// Send data and get response
$cap = $_POST['g-recaptcha-response'];
$ch = curl_init('https://www.google.com/recaptcha/api/siteverify?secret=6Lc4vP4SAAAAAGOM8ERb1pYSBfHjiMGb9bnGVtog&response='.$cap);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($result = curl_exec($ch);
curl_close($ch);
print_r($result);
}
?>
I create demo with more clear and very sort line of code.
HTML:
<html>
<head>
<title>Addweb solution Pvt Ltd Google recapcha demo - Codeforgeek</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<h1>Google reCAPTHA Demo</h1>
<form id="comment_form" action="verify.php" method="post">
<input type="email" placeholder="Type your email" size="40"><br><br>
<textarea name="comment" rows="8" cols="39"></textarea><br><br>
<input type="submit" name="submit" value="Post comment"><br><br>
<div class="g-recaptcha" data-sitekey="XXXXXXXXX_SITE_KEY_XXXXXXXX"></div>
</form>
</body>
</html>
PHP:
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])){
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
//your site secret key
$secret = 'XXXXXXXXXXXXX_SECRET_KEY_XXXXXXXXXXXX';
//get verify response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['g-recaptcha-response'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
//contact form submission code goes here
$succMsg = 'Your contact request have submitted successfully.';
//Your PHP stuff for use after captcha validate success.
}else{
$errMsg = 'Robot verification failed, please try again.';
}
}else{
$errMsg = 'Please click on the reCAPTCHA box.';
}
}
?>
Please replace your site key with 'XXXXXXXXX_SITE_KEY_XXXXXXXX' and secret key with 'XXXXXXXXXXXXX_SECRET_KEY_XXXXXXXXXXXX'. Also use your mysql related logic into success validation block.
In future you need to check error message if any then you can find here.
Let me know if there is any concern regarding this. Hope this help.!
Just do a JavaScript validation for empty captcha field in the client side and do allow them to submit the form at all if it is not filled! A very good example of this is available here: ReCaptcha Validation

Php Contact us form with two submit button and will go three different email addresses

I have created one contact us form but there you be two submit button:
Button name submit will go to data this email address: sm.musa.cse#gmail.com
Button name very urgent will go to data these two email address sm_musa#hotmail.co.uk and s_m_musa#yahoo.com
I coded php in separated page and form in the index page but it’s not working. Here is the code below:
HTML code:
<form action="bin/MailHandler.php" id="ContactForm" method="post">
<div class="success"> Contact form submitted!>
<br />
<strong>We will be in touch soon.</strong>
</div>
<fieldset>
<div class="wrapper">
<label class="name">
<span class="bg">
<input type="text" name="name" value="Name:" class="input" />
</span>
<span class="error">*This is not a valid name.</span>
<span class="empty">*This field is required.</span>
</label>
</div>
<div class="wrapper">
<label class="email">
<span class="bg">
<input type="text" name="email" value="E-mail:" class="input" />
</span>
<span class="error">*This is not a valid email address.</span>
<span class="empty">*This field is required.</span>
</label>
</div>
<div class="wrapper">
<label class="phone">
<span class="bg">
<input type="tel" name="phone" value="Phone:" class="input" />
</span>
<span class="error">*This is not a valid phone number.</span>
<span class="empty">*This field is required.</span>
</label>
</div>
<div class="wrapper">
<label class="message">
<span class="bg">
<textarea rows="1" cols="1" name="message">Message:</textarea>
</span>
<span class="error">*The message is too short.</span>
<span class="empty">*This field is required.</span>
</label>
</div>
<div class="btns">
<input name="first_email_send" type="submit" value="submit" />
</div>
<div class="btns">
<input name="second_email_send" type="submit" value="very urgent" />
</div>
</fieldset>
</form>
php code:
<?php
$name= $_POST['name'];
$email= $_POST['email'];
$phone= $_POST['phone'];
$message= $_POST['message'];
$to1="sm.musa.cse#gmail.com";
$to2_1="sm_musa#hotmail.co.uk";
$to2_2="s_m_musa#yahoo.com";
$subject="You Have Recieved Mail From Customer";
$mess1= $name.$phone.$message."MUSA VAI JEITA ICCA SEITA LEKO";
$mess2_1= $name.$phone.$message."MUSA VAI JEITA ICCA SEITA LEKO";
$mess2_2= $name.$phone.$message."MUSA VAI JEITA ICCA SEITA LEKO";
//$send_contact= mail( $to,$subject,$email,$mess);
if(isset($_POST['first_email_send']))
{
$send_contact= mail( $to1,$subject,$email,$mess1);
if($send_contact){
echo "Thank for submitting you details we've received your Details. One of our sales member contact you as soon as possible";
}
else {
echo "ERROR";
}
}
if(isset($_POST['second_email_send']))
{
$send_contact1= mail( $to2_1,$subject,$email,$mess2_1);
$send_contact2= mail( $to2_2,$subject,$email,$mess2_2);
if($send_contact1 && $send_contact2){
echo "Thank for submitting you details we've received your Details. One of our sales member contact you as soon as possible";
}
else {
echo "ERROR";
}
}
/*if($send_contact){
echo "Thank for submitting you details we've received your Details. One of our sales member contact you as soon as possible";
}
else {
echo "ERROR";
}*/
?>
The issue is the way you are checking for how data is submitted. You need to change two things
Make the name of submit buttons same, say "submit"
<div class="btns">
<input name="submit" type="submit" value="submit" />
</div>
<div class="btns">
<input name="submit" type="submit" value="very urgent" />
</div>
Post Data is submitted as key value pairs. Value of the submit button will hint you which button was clicked.
Check the value of the 'submit' parameter in the POST and then make a decision. i.e modify your php code like this
if($_POST['submit'] == 'submit')
{
$send_contact= mail( $to1,$subject,$email,$mess1);
if($send_contact){
echo "Thank for submitting you details we've received your Details. One of our sales member contact you as soon as possible";
}
else {
echo "ERROR";
}
}
if($_POST['submit'] == 'very urgent')
{
$send_contact1= mail( $to2_1,$subject,$email,$mess2_1);
$send_contact2= mail( $to2_2,$subject,$email,$mess2_2);
if($send_contact1 && $send_contact2){
echo "Thank for submitting you details we've received your Details. One of our sales member contact you as soon as possible";
}
else {
echo "ERROR";
}
}
Reference: https://stackoverflow.com/a/56/1523245

How to Get Contact Form Working

Okay so I am fairly new to web designing. How do I get the contact form on my current theme to work? This is the current html.
I need to know how to code the PHP file; is this correct?
<div class="form row-fluid clearfix">
<div class="field span5">
<label>Your name:</label>
<input type="text" value="" class="req" placeholder="Placeholder text..." />
</div>
<div class="field span5">
<label>Your email:</label>
<input type="email" value="" class="req" />
</div>
<div class="clearfix"> </div>
<div class="field full">
<label>Your comment:</label>
<textarea class="span12" cols="2" rows="7"></textarea>
</div>
<button class="extruded"><span>Submit</span></button>
</div>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: iclear';
$to = 'sales#tangledindesign.com';
$subject = 'Hello';
?>
And how do I link the PHP file for that contact form?
Step 1
Wrap your fields with a form HTML element that has its action property set to your php processing page
Step 2
Name the form fields according to what the php file expects
Step 3
Add some validation
Step 4
Submit and test
Example
HTML
<form action="process.php" method="post">
First Name: <input type="text" name="first_name">
<input type="submit">
</form>
PHP
<?php
$first_name=$_POST["first_name"];
if($first_name=="John")
{
echo "Hi John!";
}
else
{
echo "Sorry Buddy, Don't really know you";
}
?>
Note
The reason why i did not provide you a full solution is that you mentioned you are a newbie in that programming, and it would be injustice to just solve your problem and not guide you how to do it
You need to wrap your HTML with the tag, and don't forget to get include the submit button:
<form action="process.php" method="post">
<div class="form row-fluid clearfix">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="message">
<input type="submit" name="submit">
</div>
</form>
Then here is the php (process.php) file to get all values from your HTML form:
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: iclear';
$to = 'sales#tangledindesign.com';
$subject = 'Hello';
Hope this help.
Try this code
<?php
$toaddress ="youremail#domain.com" //change to your email address
$error ="";
if($_SERVER['REQUEST_METHOD']=="POST") {
$name=$_POST['name'] ;
$email=$_POST['email'] ;
$comment=$_POST['comment'] ;
if(!isset($name) || $name==""){
$error .="Please Enter your name <br/>";
}elseif (!isset($email) || $email==""){
$error .="Please Enter your email Address.<br/>";
}elseif(!isset($comment) || $comment==""){
$error .="Please Enter your Comments.<br/>";
}
if ($error ==""){
mail($toaddress,"Contact form",$comment)
}
}
?>
<?php echo $error ;?>
<form method='post' action='' enctype='multipart/form-data' id='news_form' name='post_form' >
<div class="form row-fluid clearfix">
<div class="field span5">
<label>Your name:</label>
<input name="name" type="text" value="" class="req" placeholder="Placeholder text..." />
</div>
<div class="field span5">
<label>Your email:</label>
<input type="email" value="" class="req" name="email" />
</div>
<div class="clearfix"> </div>
<div class="field full">
<label>Your comment:</label>
<textarea class="span12" cols="2" rows="7" name="comment"></textarea>
</div>
<input type="submit" value="submit" />
</div>
</form>

Categories