Google ReCaptcha Display with Image & Client Side Validation on Form Submit - php

I have followed
How to Validate Google reCaptcha on Form Submit
I have below code in my index.php
<!DOCTYPE HTML>
<html>
<head>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<form method="post" action="post.php">
<div class="g-recaptcha" data-sitekey="6XXXXXXXXXXXXwdsf0K8HbXXXXXXX"></div>
<input type="submit" value="Submit" />
</form>
</body>
</html>
post.php
$response = $_REQUEST['g-recaptcha-response'];
$secret = '6XXXXXXXXXXXXwdsf0K8HbJNvMw-XXXX';
$server = $_SERVER['REMOTE_ADDR'];
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $response.'&remoteip='.$server);
$response = json_decode($response, true);
if ($response["success"] === true) {
echo "Logged In Successfully";
} else {
echo "You are a robot";
}
exit;
Above code is working fine.
How to do client side validation? It's not showing Captcha with Images Option.
I already done below

This is the standard behavior of the Recaptcha library does not display the first time the control over the images.
Try to view or post the page many times and you will see that the images not eventually appear.
If you want to do some client side validation on other additionnals fields, you must use jQuery or standar library like bootstrap or foundation, like this or this. You can see of full example of a working script here (inspired from bootstrap script and HTML 5 capabilities) :
This version of the script is the same all over Internet. No more client side validation for this ! Have a look to a reference : codepen.io signup
For example :
<!DOCTYPE HTML>
<html>
<head>
<link href="../../dist/css/bootstrap.min.css" rel="stylesheet">
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<form class="signin-form" method="post" action="post.php">
<!-- for example : Email and password validation (HTML 5) -->
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<!-- Site-key for automated tests -->
<div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</body>
</html>
And here a sample code pen.

Related

Save files in forms after submit with php

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="header">
<H2>Login</H2>
</div>
<form method="post" action="https://..." enctype="multipart/form-data">
<?php include 'errors.php'; ?>
<div class="input-group">
<input type="text" name="username" placeholder="Username..." value="<?php echo $username; ?>">
</div>
<div class="input-group">
<input type="password" name="password_1" placeholder="Password...">
</div>
</div>
<div class="input-group">
<input type="file" name="image" placeholder="Image..." value="<?php echo $image; ?>"> // The File doesn't get echo in after submit and an error
</div>
<div class="input-group">
<button type="submit" name="login" class="btn">Login</button>
</div>
</form>
</body>
</html>
This Form is to register Users with an Image. After submit I check if there Name is all ready taken and look for other errors if there is an error I want that everything is still in the Form except the password. It is working with the Username but not with a file (Image). So how can I do that?
It is by default impossible to set a default value for a file picker due to security reasons
Learn more about it here
Others have explained why you can't do it. But if it is very important for you to achieve this behaviour (retaining all elements if there is an error in submission details), you can do this by setting up Ajax calls.
Since you would also add preventDefault() to the submit button event handler, the page won't be refreshed and the user won't lose entered data.
Your first ajax call will verify if entered data is valid. And then, if the response is positive, you send another ajax request to process the form submission.

Register form submitting when reCAPTCHA isn't validated

I added reCAPTCHA to my registration form and when I tested the page, I noticed I can still register a new account without verifying using reCAPTCHA. When I leave one of the text boxes blank I receive "Please verify that you are Human." This message is supposed to appear when a user fills out the form and forgets to verify. I tried many different if statements provided by stack overflow and other websites and the issues still weren't solved. I also tried messing around with my form with "method" and "action".
Here is my registration form
<?php include('server.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Register for Redchan</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<img alt="4chan" src="/image/pepe-popcorn.gif" width="300" height="120">
<div class="header">
<h2>Register for Redchan</h2>
</div>
<?php
//Check for form submission
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
//Get form submission data
$username = $_POST['username'];
$email = $_POST['email'];
//Set verification information for the Google reCAPTCHA API
$secretKey = "----------------------------------";
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
//Call Google reCAPTCHA API
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
$response = file_get_contents($url);
//Decode API response and generate response
$verification = json_decode($response, true);
if ($verification['success'])
echo "<p>Verification success!</p>";
else
echo "<p>Please verify that you are a Human.</p>";
}
?>
<form method="post" action="register.php">
<?php include('errors.php'); ?>
<div class="input-group">
<label>Username</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>Email</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm password</label>
<input type="password" name="password_2">
</div>
<div class="g-recaptcha" data-sitekey="-------------------------------"></div>
<div class="input-group">
<button type="submit" class="btn" name="reg_user">Register</button>
</div>
<p>
Already a member? Sign in
</p>
</form>
</body>
</html>
You need to set the captcha field itself to required which by default is not.
You could try something like this:
<script type="text/javascript">
window.onload = function() {
var $recaptcha = document.querySelector('#g-recaptcha-response');
if ($recaptcha) {
$recaptcha.setAttribute("required", "required");
}
};
</script>

how to generate dynamically html web pages with content, when user hit submit button?

i am working on a project in which user have to ask a question through fill a form. my question is that when user fill the form and ask the question the php automatically generate the html web page. for example if user asks what is stackoverflow then url be like localhost/what-is-stackoverflow , and by clicking on this link this link show the other content which users filled.
here is my code
<?php include("header.php");
require("dbconnect.php");
if(isset($_POST['post'])){
$user_email = $_POST['user_email'];
$user_name = $_POST['user_name'];
$question_title = $_POST['question_title'];
$question_body = $_POST['question_body'];
$question_title = htmlentities($question_title);
$question_body = htmlentities($question_body);
$insert_question = mysqli_query($con,"insert into questions values('','".$user_email."','".$user_name."','".$question_title."','".$question_body."','".php_slug($question_title)."')");
}
function php_slug($question_title)
{
$slug = preg_replace('/[^a-z0-9-]+/','-' , strtolower($question_title));
return $slug;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<link href="favicon.ico" rel="shortcut icon" type="img/ico">
</head>
<body>
<div class="container">
<div class="col-lg-7 " >
<div class="form-group ">
<form name="submit_question" action="" method="post">
<label for="user_email" class="control-label " > Enter Your Email Address We Will Mail You Answer </label>
<input type="email" class="form-control" name="user_email" placeholder="Enter Your Email We Will Mail You Answer Of Your Question" required/>
<br >
<label for="user_name" class="control-label " > Enter Your Name </label>
<input type="text" class="form-control" name="user_name" placeholder="Enter Your Name" required/>
<br >
<label for="question_title" class="control-label " > Enter Your Question Subject </label>
<input type="text" class="form-control" name="question_title" placeholder="Enter Question Subject" required/>
<br >
<label for="question_body" class="control-label " > Question Body </label>
<textarea class="form-control pull-middle" rows="20" placeholder="Enter Post Content" name="question_body" required/> </textarea>
<div class="btn btn-group pull-right">
<br>
<br>
<button type="submit" class="btn btn-primary" name="post">
<span class="glyphicon glyphicon-plus"></span> Submit Question
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script src="js/bootstrap.js" > </script>
<?php include("footer.php");?>
</body>
I think
1. You have to post the all content in your <form action=""> page.
2. Get that all data in variables then replace all special characters like space, ? etc from question with '-'.
3. the create url with this updated question with the url parameters like name, email
$url=localhost/what-is-stackoverflow?email=email#gmail.com&name=abc
4. use .htaccess file to rewrite url
RewriteRule ^(a-zA-z)$ filename [L]
5. redirect to that url with url parameters.
redirect($url,'refresh');
6.on that page get all url parameters.
$myFile = $questiontitle.".html"; // or .php
$fh = fopen($myFile, 'w'); // or die("error");
$stringData = "<html><head><title>".$questionbody."</title></head><body></body></html>";
fwrite($fh, $stringData);
You can create html file and add html content programmatically by php

php form action with recaptcha check

Working on a simple contact form, and I'm trying to integrate Google ReCaptcha to eliminate the spam I started receiving.
Right now it's checking to see if the ReCaptcha is successful. If it's not, it just currently reloads the page and resets the form. If it is, I'd like it to fire the receiving contact form php page and pass the form values along with it.
It's getting hung up on that part. Any help would be greatly appreciated.
<?php
// grab ReCaptcha library
require_once "recaptchalib.php";
// your secret key
$secret = "XXXXXXXXXXXXXXXXXXXXXXXX";
// empty response
$response = null;
// check secret key
$reCaptcha = new ReCaptcha($secret);
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Contact Form</title>
<link href='https://fonts.googleapis.com/css?family=Work+Sans:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="assets/form-basic.css">
</head>
<body>
<div class="main-content">
<?php
$action = '';
if ($response != null && $response->success) {
$action = "contactengine.php";
} else {
?>
<form class="form-basic" action="<?php echo $action ?>" method="post">
<div class="form-title-row">
<h1>Get in Touch</h1>
</div>
<div class="form-row">
<input type="text" name="Name" placeholder="Name" required>
</div>
<div class="form-row">
<input type="email" name="Email" placeholder="Email" required>
</div>
<div class="form-row">
<textarea name="Message" placeholder="Message" required></textarea>
</div>
<div class="form-row">
<div class="g-recaptcha" data-sitekey="fdgafafdadfgsdfgrafgaRlifgsfgserysrtyc3H"></div>
</div>
<div class="form-row">
<button type="submit" name="submit" value="submit">Send</button>
</div>
</form>
<?php } ?>
</div>
<script src='https://www.google.com/recaptcha/api.js?hl=en'></script>
</body>
</html>
You can either move the captcha checking code into the receiving contact form page, or add the contact form processing logic in the main page. You probably want to use the last approach.

JQuery event.preventdefault and php

I have a question concerning event.preventdefault. I used it on my client side validation just to make sure a username and password were filled in. However when I pressed the submit button and passed the validation on to php I got nothing. I mean when I checked if the form was submitted and did an echo to check I got nothing. But when I did (!isset($_POST['whatever']) I got something. Same goes for check if the fields were empty. I got nothing when I did empty, but got something when I did !empty
Jquery/html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="css/verneyCustom.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<!-- cms login form -->
<form action="login.php" method="POST" class="form-signin" id="cms-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<span class="text-center" id="jsError"></span><!-- display client side errors -->
<input type="text" class="form-control" id="username" placeholder="Username" autofocus><br/>
<input type="password" class="form-control" id="password" placeholder="Password"><br/>
<input type="submit" class="btn btn-lg btn-primary btn-block" id="loginToSystem" value="Sign In">
</form>
</div>
<!-- include jquery v1.10.2 library to validate client side -->
<script src="js/jquery.js"></script>
<script>
//if the form is submitted check if values are ok
$("#cms-signin").submit(function(event){
if($('#username').val() == "" || $('#password').val() == ""){
event.preventDefault();
$("#jsError").html('You must fill in the form.');
}else if($('#username').val() == ""){
event.preventDefault();
$("#jsError").html('Username is required.');
}else if($('#password').val() == ""){
event.preventDefault();
$("#jsError").html('Password is required.');
}
});
</script>
</body>
</html>
php code
<?php
//include the connection to the cms database
require_once($_SERVER['DOCUMENT_ROOT'].'/vcm/_cms/resources/database_connect.php');
//check if the form was sent
if(isset($_POST['loginToSystem'])){
echo 'o';
//create an array for errors
$errors = array();
//check if the username and password fields are empty
//yes we did a check if jquery on the front but some people disable javascript
if(empty($_POST['username']) || empty($_POST['password'])){
echo 'empty';
}else{
echo 'ok';
}
}
echo'p';
?>
So basically it echo's 'p' no matter what, but will only echo 'o' if isset is changed to !isset. It will echo empty when left as is, and ok when changed to !empty
as adeneo explained you must add name
<form action="login.php" method="POST" class="form-signin" id="cms-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<span class="text-center" id="jsError"></span><!-- display client side errors -->
<input type="text" class="form-control" name="username" id="username" placeholder="Username" autofocus><br/>
<input type="password" class="form-control" name="password" id="password" placeholder="Password"><br/>
<input type="submit" class="btn btn-lg btn-primary btn-block" id="loginToSystem" value="Sign In">
</form>
also you need && not ||
$("#cms-signin").submit(function(event){
if($('#username').val() == "" && $('#password').val() == ""){
event.preventDefault();
$("#jsError").html('You must fill all fields.');
}
});

Categories