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

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
}
?>

Related

Why do I get "Undefined index: recaptcha_response_field"?

This is my form code:
echo '
<div class="ctext" id="form">
<table><form method="post" action="prashanja.php">
<tr><td>Name:</td><td><input type="text" name="name"/></td></tr>
<tr><td>Question:</td><td><textarea cols="55" rows="4" name="prashanje"> </textarea></td></tr>
<tr><td></td><td >' . recaptcha_get_html($publickey) . '<button name="btn" value="submit">Enter</button></td></tr>
</form></table>
</div>';
And this is the validation code:
if (isset($_POST['btn'])) {
$name = mysql_real_escape_string(strip_tags($_POST['name']));
$prashanje = mysql_real_escape_string(strip_tags($_POST['prashanje']));
$date = time();
# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;
# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
$resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
$query = "INSERT INTO prashanja VALUES(NULL,'$name','$prashanje','','$date')";
if (!mysql_query($query))
echo 's... happens';
else
echo 'cool';
} else {
# set the error code so that we can display it
$error = $resp->error;
}
}
}
These segments are on the same page. The first segment generates the form and the second segment checks if the correct button is pressed, initializes the variables and than checks the recaptcha and does some operations. I get the error "Undefined index: recaptcha_response_field". I suspect that recaptcha won't work if the validation is done on the same page as the form that sent the variables. Are my suspicions correct and is it better if I move the validation code to another file?
It works if you validate on the same page.
You are accessing the variable for checking:
if ($_POST["recaptcha_response_field"]) {
That most likely causes the error, it should be
if (isset($_POST["recaptcha_response_field"])) {
Move the
form
tag outside of the
table
tag. I don't know why but it worked.

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 page not sending data to .csv

I have created a PHP page (see code below) that is supposed to validate the information entered into the webform prior to submitting it, to ensure that all fields have been completed. If any fields have been left blank, it is supposed to display an error message; if all fields have been filled in, it is supposed to send the data to a .csv file. The problem is that it is not validating the fields, nor is it sending the data to the .csv. I have tried deleting the .csv and then submitting the webform; it creates a .csv with commas separating the entries, but there are no entries (i.e. no text, only commas).
Does anybody know why this might be?
Any assistance would be appreciated.
Thanks in advance!
Here is the code:
<form action="form_mailer.php" method="post">
<table>
<tr><td>Which is your name?</td>
<td><input type="text" name="formName" maxlength="50" value="<?=$varName;?>"></td></tr>
<tr><td>What is your occupation?</td>
<td><input type="text" name="formOccupation" maxlength="50" value="<?=$varOccupation;?>"></td></tr>
</table>
<input type="submit" name="formSubmit" value="Submit">
</form>
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formName']))
{
$errorMessage .= "<li>You forgot to enter your name!</li>";
}
if(empty($_POST['formOccupation']))
{
$errorMessage .= "<li>You forgot to enter your occupation!</li>";
}
$varName = $_POST['formName'];
$varOccupation = $_POST['formOccupation'];
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
<?php
if($errorMessage != "")
{
echo("<p>There was an error:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
else
{
$fs = fopen("data.csv","a");
fwrite($fs,$varName . ", " . $varOccupation . "\n");
fclose($fs);
}
?>
UPDATE:
Hi,
Many thanks for the responses.
I've realised where I have gone wrong now........I had the form action as 'form_mailer.php', which is not the form page itself but another page that performs further actions with the data provided on the webform.
I have now brought the 'form_mailer' coding into the webform .php and have changed the 'action' of the webform page so that it effectively submits to itself, but now I need to redirect to the form_mailer page following successful submission of the webform or display a thank you message........don't suppose anybody knows how I can do this? If you could provide instructions for how to do both that would be great as I can then choose the one I prefer that would be best for my needs.
Thanks again!
I have checked your code and it's working fine and also store data in csv file.
Probably you should make these vars global:
<?php
global $varName, $varOccupation
...
... probably in both <?php blocks.

javascript prompt box for reCAPTCHA

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.

custom 404 doesn't work properly

I am using this code on my website (It is included in 404.php):
<?php
if (isset($_POST["op"]) && ($_POST["op"]=="send")) {
/******** START OF CONFIG SECTION *******/
$sendto = "myemail#gmail.com";
$subject = "Website Contact Enquiry";
/******** END OF CONFIG SECTION *******/
$message = $HTTP_POST_VARS['message'];
$headers = "From: $email\n";
$headers . "MIME-Version: 1.0\n"
. "Content-Transfer-Encoding: 7bit\n"
. "Content-type: text/html; charset = \"iso-8859-1\";\n\n";
$request = $_SERVER["REQUEST_URI"];
$self = $_SERVER["PHP_SELF"];
// Build the email body text
$emailcontent = "
-----------------------------------------------------------------------------
WEBSITE CONTACT ENQUIRY
-----------------------------------------------------------------------------
$request
$self
$message
";
if (!trim($message)) {
echo "<p>Please go back and type a Message</p><p><a href='javascript: history.go(-1)'>Click here to go back</a>.</p>";
}
// Sends out the email or will output the error message
elseif (mail($sendto, $subject, $emailcontent, $headers)) {
echo "<br><br><p><b>Thank You </b></p><p>We will be in touch as soon as possible.</p>";
}
}
else {
?>
And this is my form
<form action="http://www.ahornblume.ch/404.php" method="post">
<INPUT NAME="op" TYPE="hidden" VALUE="send">
<textarea name="message" cols="25" rows="4" placeholder="Wenn Sie eine Antwort wünschen, vergessen Sie bitte ihre email Adresse nicht."></textarea><br>
<input name="submit" type="submit" value="Send Message">
</form>
I am redirecting all 404 errors in my htaccess file like so:
ErrorDocument 404 /404.php
If I go to ahornblume.ch/404.php everything works and I can use the form to send emails.
But, if I go to ahornblume.ch/something the contact form doesn't work.
Your form does not have an action specified so it will submit to the URL that was used to display the form.
In case of ahornblume.ch/404.php it will submit to 404.php and it will work.
In case of ahornblume.ch/something it will result in a 404 error that will just display the 404.php page, but the form post will have been discarded.
To fix, specify an action with an absolute path/404.php
If you are including the contact form you might want to check the links first! It's probably just a wrong link. Avoid using stuff like action="../php/contact_form.php". With include/require/require_once, I always opt for $root = realpath($_SERVER["DOCUMENT_ROOT"]);require_once($root."/path/to/file/myfile.php");
So if the contact form is displaying but when you click submit nothing happens, the cause is most likely that the server cannot locate the "action" php file. You have two options:
1: instead of <form action="../your_file.php" use the full link. <form action="http://yoursite.com/path/to/your/file/yourfile.php"
2. Always make use of root for include, require and require_once and use an additional variable like $url=http://www.yoursite.com and whenever you need to insert links, use PHP, as follows:This is a link. It may look like a lot of trouble, but it will make your life much much easier in some cases. Switching to https or any kind of global modification will mean that you only have to change 1 variable, $url. Every single link will then automatically be updated. If you know for a fact that you don't need this, option number 1 will do.
Are you using javascript/ajax/jquery for the form submission? If you are send a post request like that, check the link in the .js file or wherever you have the code and use an absolute path for the post request.

Categories