javascript prompt box for reCAPTCHA - php

I'm trying to make an automatic prompt box which displays the error of an incorrect reCAPTCHA input, at the moment I have a function 'redirect_to' which links to an identical page, which i planned to just input a error in text form. If anyone could help me with this I'd be much appreciated, i'm not had too much experience with javascript.
require_once($_SERVER['DOCUMENT_ROOT'] . '/recaptcha/recaptchalib.php');
$privatekey ="*********";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER['REMOTE_ADDR'],
$_POST['recaptcha_challenge_field'],
$_POST['recaptcha_response_field']);
$str_result = "";
if (!$resp->is_valid) {
redirect_to("login_recap.php");
// What happens when the CAPTCHA was entered incorrectly
$message = "The reCAPTCHA wasn't entered correctly. Go back and try it again. (reCAPTCHA said: " . $resp->error . ")";
echo $message;
exit();
}

You can redirect back to the login page with a GET parameter such as: login.php?captchaError=1. Then on your login page, simply add:
<?php
if(isset($_GET['captchaError]))
{
echo("<script type='text/javascript'>
alert("Captcha entered incorrectly.");
</script>
");
}
?>
That will check if there is an error and output some JS to display the alert.

Related

Can't get ReCAPTCHA to work (or even display!)

I'm sure it's simple but I can't see it :)
I'm trying to add a reCAPTCHA into the code for an existing site with a little contact form.
I have the keys from Google (censored in the examples of course) but I can't even get it to display the CAPTCHA, let alone anything test if the filtering is working.
I've added the reCAPTCHA code into the page:
index.html:
form name="f1" method="post" action="mail2.php" onsubmit="return verify();">
<p><label>Your Name <span>(*)</span></label><input type="text" name="name" /></p>
<p><label>Your Email</label><input type="text" name="email" /></p>
<p><label>Your Phone No: <span>(*)</span></label><input type="text" name="phone" /></p>
<p><label>Other messages</label><textarea name="messages" rows="" cols=""></textarea> </p>
<?php
require_once('recaptchalib.php');
$publickey = "6LdrxxxxxxxxxxxxxxJr"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<p style="padding-right:36px; float:right;"><input name="" type="image" src="images/submit_btn.png" /></p>
</form>
And in the mail2.php
<?php
require_once('recaptchalib.php');
$privatekey = "6LxxxxxxxxxxxxxxxxxxqZYiH";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
require_once 'mailer/class.phpmailer.php';
$mail = new PHPMailer();
----followed by the standard PHPMailer content----
The index page just displays as standard with no CAPTCHA section displayed, trying to send an email results in failure with some PHP code displayed.
I'd really appreciate if someone with a mind larger than mine who eats & breathes reCAPTCHA could cast their eye, laugh & point at where I've gone wrong. :)
Looking to be educated rather than just a fix. My skills lie in content rather than coding I'm afraid.
(And how do I insert a code block in the editor? Surely don't have to indent each line by 4 spaces individually?)
Many Thanks.
I can help because I have it working farther than you, but I need help on this subject too.
To begin, you need this line of code in your html header (before the </head> tag:
<script src="https://www.google.com/recaptcha/api.js?fallback=true" async defer></script>
Then in the body of your html, and somewhere inside of your form (between your <form> ... </form> tags) you need the following code:
<div class="g-recaptcha" data-sitekey="....your site key here...."></div>
Then in your PHP processing file (the file that your form posts to and receives the form variables you need the following code:
$response_string = $_POST['g-recaptcha-response'];
$secret_key = "...put in your secret key here...";
$resp = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret_key&response=$response_string");
if($resp != '{ "success": true }')
{ $problem = "failedreCAPTCHA";
header("Location: http://www.yourwebsite.com/...pagetohandlefailedentry...php?problem=$problem");
die('Sorry, you entered the wrong value in the Human CAPTCHA challenge. Please try again.');
}
This code works great except for the "if($resp != '{ "success": true }')" part of it. Because the variable $resp get filled with from google is "{ "success": true }" which turns out to be a JSON object and I don't know how to test for "true" with PHP and a JSON object.
So... someone, please help.
This appears to be working for me, using Google's new "no Captcha reCaptcha". This largely builds off of Brook's answer, but includes the ip, parses the json, and tests for success.
<?php
$gSecret = "...put in your secret key here...";
$gResponse = $_POST['g-recaptcha-response'];
$gRemoteIp = $_SERVER['REMOTE_ADDR'];
$gResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$gSecret&response=$gResponse&remoteip=$gRemoteIp");
$resp = json_decode($gResponse);
if (!$resp->success) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error-codes . ")");
} else {
// Your code here to handle a successful verification
}
?>

Code is not working when reCaptcha input is correct

I am trying to implement Google's reCaptcha on my website's query form in php.
When the CAPTCHA is entered incorrectly,
I get: "No. CAPTCHA is not entered correctly".
But when the CAPTCHA is entered correctly,
What I expect: "Everything looks good" OR "CAPTCHA is correct but other values are incorrect."
What I get: Blank Page
Here is how I am implementing it:
$var1 = $_POST["var1"];
$var2 = $_POST["var2"];
require_once('recaptchalib.php');
$privatekey = "<private key I got from reCaptcha>";
$respCaptcha = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if(!$respCaptcha->is_valid) {
echo "No. CAPTCHA is not entered correctly";
} elseif( is_numeric($var1)
&& preg_match("/^[a-zA-Z ]*$/",$var2)) {
echo "Everything looks good";
} else {
echo "CAPTCHA is correct but other values are incorrect.";
}
Please help. What am I doing wrong here?
Try putting the if just inside the else...
Also is this directly pasted because the line
'Do something...' is not commented

HTML Form with PHP Captcha Plugin, I'm running into some issues

I have looked for similar questions and I did not find my particular case.
I am using the PHP Captcha plugin within a form that I have. I handle the incorrect and correct captcha entries very similar. If the user's phrase is correct I throw a javascript "success" alert, send the form email, and then send them back to the last page. If incorrect I throw a javascript "your incorrect" alert and send them back to the last page.
My problem- if they are incorrect I need to refresh Captcha because with an incorrect Captcha entry you will always need to refresh the image for another attempt. Also if they are correct I want the field cleared but only cleared when correct, if incorrect I want to keep the forms data. How can I do this?
Here is my PHP captcha code so you can see my attempt. Let me know if you want the html... (also I checked all entries with JS before POST)
<?php
/*set email*/
$myemail = "email#email.com";
/* Check all form inputs using check_input function */
$name = $_POST['name'];
$companyName = $_POST['companyName'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$TimeForContact = $_POST['TimeForContact'];
$aval = $_POST['aval'];
$messageFromFrom = $_POST['message'];
$firstTime = $_POST['firstTime'];
$subject = "Some Subject";
require_once('recaptcha-php-1.11/recaptchalib.php');
$privatekey = "*someprivatekey*"; //I took this out for the question
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
echo '<script type="text/javascript"> alert ("You have inserted the wrong phrase in the Captcha box. Please try again! Thank you."); window.history.back();</script>';
exit();
} else {
$message = "some message
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
echo '<script type="text/javascript"> alert ("Success! You have emailed your submission. Please await our response. Thank you."); window.history.back()</script>';
exit();
}
?>
I originally tried reloading the page through JS, like:
window.reload(history.back());
or
window.location.reload(history.go(-1));
no success with either + multiple combinations similar to that.
So to reiterate the question:
How can I refresh form/captcha when desired
OR
What is your practiced behavior for submitting a captcha form?
Thank you.
You should be doing something like this. Essentially checking for errors and pushing errors into an error array that you can later loop over and display to the user. Upon submit, you check the recaptcha and if its invalid, it will automatically clear the field. Do not use alerts or exit() or anything of that sort, a simple $errors array should suffice.
//untested code
<?php
//check to make sure they submitted the form
if(isset($_POST['submit'])){
$errors = array();
$myemail = "email#email.com";
$name = $_POST['name'];
$companyName = $_POST['companyName'];
/* ... */
//recaptcha check
require_once('recaptcha-php-1.11/recaptchalib.php');
$privatekey = "*someprivatekey*";
$resp = recaptcha_check_answer (
$privatekey,$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]
);
//validate all data here
if (!$resp->is_valid) {
array_push($errors, "recaptcha invalid please try again");
}else if( /* name is invalid */) {
array_push($errors, "name invalid");
}else if (){
/* keep validing ...... with else if*/
}
/*....*/
else{
//everything validated so were good
mail($myemail, $subject, $message);
}
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form action="process.php">
<!-- Your form here, "process.php" is this page itself -->
<input name="submit" type="submit" value="Send">
</form>
</body>
</html>

PHP reCaptcha won't validate

I'm trying to get reCaptcha working with a form on my website and for some reason I keep getting an error that the wrong captcha was entered. Does anyone see anything wrong with my code?
require_once('includes/recaptchalib.php');
$publickey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$privatekey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
if (isset($category)) {
if ($edit == 'edit') {
include "includes/updatelisting.php";
} else {
$response = recaptcha_check_answer($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if ($response->is_valid) {
include "includes/insertlisting.php";
} else {
echo "Eh, That wasn't right. Try Again.";
}
}
} else {
Here is the code in the actual form..
// Display the reCaptcha form
echo recaptcha_get_html($publickey, $error);
I found the issue. Apparently my tags were inside the tags. Once I put the form tags outside the table tags everything worked perfectly. Very strange. Here is a link to the answer I found Need help with reCAPTCHA - keep getting incorrect-captcha-sol
When you call echo recaptcha_get_html($publickey, $error); did you already have $error declared?
You might want to declare it first (and yes, make it a string with one space):
$error = ' ';
echo recaptcha_get_html($publickey, $error);
Also, check to see if $category really is set before trying to validate.

Change reCAPTCHA response to alert() instead of loading new page

I'm using reCAPTCHA and I'd like to show the response if the CATPCHA was filled in incorrectly as an alert(); rather than it loading a new page. How can I do that?
This is the form action:
<form id="form" method="POST" action="verify.php">
With this in the verify.php file:
<?php
require_once('recaptchalib.php');
$privatekey = "(my key)";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
}
?>
Call your method on form submit like--
<form id="form" method="POST" action="verify.php" onsubmit="mymethod()" >
OR use jquery, something like that --
<script>
$("form").submit(function() {
if ($("input:first").val() == "correct") {
$("span").text("Validated...").show();
return true;
}
$("span").text("Not valid!").show().fadeOut(1000);
return false;
});
</script>
You can write the Javascript for the alert on the new page.
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
echo("<script>alert('The reCAPTCHA wasn't entered correctly. Go back and try it again.');</script">);
die();
} else {
// Your code here to handle a successful verification
}

Categories