Strange thing with Google nocaptcha - php

I have a strange problem with Google Captcha. I've tried all kinds of php codes from different tutorials, but the result is exactly the same every time...
The problem is this:
it shows up correctly
if you check the box, it works correctly
if you then send the form it works correctly
but... if you don't check the box, the form is still sent!
So, in other words, it's only on the form as a decorative piece. What could be the problem? It's probably something very simple, but I'm totally missing it.
Help or insights are very much appreciated! Thanks in advance!
Addendum
The following is the code that came with the template I used:
require_once('recaptcha-php-1.11/recaptchalib.php');
if ($use_captcha == 1) {
$resp = null;
$error = null;
$reCaptcha = new ReCaptcha($secret);
$secret = "MY SECRET KEY HERE";
$captcha_error_message = '<div class="pi-alert-danger fade in"><button type="button" class="pi-close" data-dismiss="alert"><i class="icon-cancel"></i></button><p>Bewijs dat je geen robot bent!</p></div>';
if (isset($_POST["captcha_response"]) && $_POST["captcha_response"] != '') {
$resp = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["captcha_response"]
);
if ($resp && $resp->success != true) {
echo $captcha_error_message;
exit();
}
} else {
echo $captcha_error_message;
exit();
}
}

You have to check if the captcha was solved (at your PHP-Script which do anything with the Form-data)
Like this:
function checkCaptcha($recaptchaResponse) {
$recaptchaPrivateKey = 'Your Private Key';
if(! $recaptchaResponse)
return false;
$recaptchaObj = new ReCaptcha($recaptchaPrivateKey);
$response = $recaptchaObj->verifyResponse($_SERVER["REMOTE_ADDR"], $recaptchaResponse);
if($response != null && $response->success)
return true;
return false;
}
If you don't include a function like this to your form function, your server will say, the form is okay, because it don't know about the captcha.
Note, that you have to include the Google-captcha Libarys-File as well. You can find it here:
https://github.com/google/recaptcha/blob/1.0.0/php/recaptchalib.php (Worked for NoCaptcha as well)

Related

Form Post Data As Array Value

I'm trying to integrate an API builder to my control panel through a form or post data. I can't figure out how to put the post data as the value for the array.
I tried using print_r($_POST['VALUE']) with and without quotes.
I tried using just $_POST['VALUE'] with and without quotes.
I also tried to set $value = $_POST['VALUE'] then using $value with and without quotes but that caused an error 500.
Here is the code I am trying to use:
$res = $api->remoteCall('requestLogin', array(
'type' => 'external',
'domain' => 'print_r($_POST['domain'])',
'lang' => 'en',
'username' => 'print_r($_POST['uname'])',
'password' => 'print_r($_POST['pass'])',
'apiUrl' => '127.0.0.1',
'uploadDir' => '/web/'.print_r($_POST['domain']).'/public_html',
I apologize as I am new to PHP, but thank you in advance.
I'm not sure what other logic is being done there, how the post variables are being sent to the script your sample code is running on, or any of the other details which might point towards a more complete solution but here are some basic tips to help you troubleshoot.
The post variables should be formatted like this:
$res = $api->remoteCall('requestLogin', array(
'domain' => $_POST['domain'],
You can dump the entire post array to the screen by doing
print_r($_POST);
This should output your array to the screen so you can verify that you're receiving the post data in the code and should help you fix any typos or misnamed post variables. If the array has the key as $_POST['domainName'] and you're echoing $_POST['domain']
You're calling code (the "form or post data") should have the post fields in place and named correctly in order for them to be sent to the script
<input type="text" name="domain">
You should be performing some basic validation on your post fields before adding them to something that's going to be stored anywhere or sent off to a third-party. At the most minimal you'll want to check that there is a value being set for the essential fields (required fields) and I'd look to make sure the values are matching requirements of the API you're passing them off to.
Several things may go wrong when using api. POST values, input values, API call or connection or maybe api response. So not only at the time of implementation and coding but also when integrating api call script with the application there should be some sort of testing and error handling in place. A simple script can be like this
$error = array();
$request = array();
$request['type'] = 'external';
if (isset($_POST['domain']) && !empty($_POST['domain'])) {
$request['domain'] = $_POST['domain'];
$request['uploadDir'] = "/web/{$_POST['domain']}/public_html";
} else {
$error[] = "Domain is empty";
}
if (isset($_POST['uname']) && !empty($_POST['uname'])) {
$request['username'] = $_POST['uname'];
} else {
$error[] = "Username is empty";
}
if (isset($_POST['pass']) && !empty($_POST['pass'])) {
$request['password'] = $_POST['pass'];
} else {
$error[] = "Username is empty";
}
$request['lang'] = 'en';
$request['apiUrl'] = '127.0.0.1';
if (count($error) > 0) {
echo implode( "<br>" , $error );
} else {
try{
$res = $api->remoteCall('requestLogin',$request);
} catch ( Exception $e ) {
print_r($e);
exit();
}
}

I managed to bypass recaptcha on server-side integration by me - What am I doing wrong?

I want to implement recaptcha in a very simple form
I have a index.html file on client-side, and a post.php server side.
I've tried to integrate recaptcha on the server site, as you can see in my code bellow.
I've made some tests, that seem to have an expected result...
The problem appeard when I tried this query
for X in `seq 0 100`; do curl -D - "http://example.com/post.php" -d
"email=email${X}%40example.com&tos=on&g-recaptcha-response[]=plm&submit="; done
The result was that I've bypassed recaptcha succesfully, and I'm not sure what the problem is.
Most probably, there's a problem in my php code, but what exactly?
post.php
<?php
$email;$submit;$captcha;
if(isset($_POST['submit']))
{
$email=filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
}
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha)
{
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6Le[whatever[7_t&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo '<h2>You are spammer ! Get the #$%K out</h2>';
}
else
{
$file = 'email-list.txt';
if (filter_var($email, FILTER_VALIDATE_EMAIL))
{
if(!(exec('grep '.escapeshellarg($email).' '.$file)))
{
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= $email . "\n";
// Write the contents back to the file
file_put_contents($file, $current);
header('Location: index.html?success='.urlencode($email));
}
else
header('Location: index.html?fail='.urlencode($email));
}
else
{
echo "$email is <strong>NOT</strong> a valid email address.<br/><br/>";
}
}
?>
index.html
...
<div class="form-group" ng-cloak>
<div class="g-recaptcha" ng-show="IAgree" data-sitekey="6LeEW[whatever]-UXo3"></div>
</div>
...
How can I solve this? English is not my native language; please excuse typing errors.
As mentioned in my comments above - file_get_contents returns a string. You need to decode the json string into a php object using the json_decode function:
$url = "https://www.google.com/recaptcha/api/siteverify?"‌
$response = json_decode(file_get_contents($url​));
if($response->success == false) {
echo "Oh no";
}

PHP Static var not working

I'm working on a Captcha class and i'm almost done, there is one thing that doesn't work
In the file where I put the form, I start with this line:
include 'captcha.php';
$captcha = Captcha::tryCaptcha(2,4,'#000', '#ffffff');
and this is the captch construct:
static $do_generate = TRUE;
function __construct($aantal_letters = 2, $aantal_cijfers = 4, $voorgrond = '#000000', $achtergond = '#ffffff') {
session_start();
if (self::$do_generate == TRUE) {
$letters = substr(str_shuffle('ABCDEGHJKLMNPQRSTUVWXYZ'),0 ,$aantal_letters);
$cijfers = substr(str_shuffle('23456789'),0 ,$aantal_cijfers);
$imgbreed = 18 * ($aantal_letters + $aantal_cijfers);
$_SESSION['imgbreed'] = $imgbreed;
$_SESSION['captcha'] = $letters . $cijfers;
$_SESSION['voorgrond'] = $this->hex2rgb($voorgrond);
$_SESSION['achtergond'] = $this->hex2rgb($achtergond);
}
}
so in other words I put my stuff in a session if the static var $do_generate == TRUE
So when I post the form, the captcha is getting checked by a procesor.php
like this:
if (Captcha::captcha_uitkomst() == TRUE) {
echo "Great";
} else {
echo "Wrong";
}
And this is the captcha function that checks the etered captcha code:
static function captcha_uitkomst() {
if (strcmp($_SESSION['captcha'], strtoupper(str_replace(' ', '', $_POST['captcha-invoer']))) == 0) {
return TRUE;
} else {
echo "test";
self::$do_generate = FALSE;
return FALSE;
}
}
If I enter a correct captcha code, it's all good, that works I get the echo great.
If wrong I get the echo Wrong,
Perfect, but.... when I go back to form (hit backspace one history back) to enter a correct captcha, it regenerates a new captcha.
In the class: captcha_uitkomst you see that I made the self::do_generate FALSE
And the echo 'TEST' works when it's false, (just for checking)
What am I doing wrong
When you hit "back", the page is reloaded. You get a new CAPTCHA.
The premise of your question is fundamentally flawed, as you have just randomly assumed that this shouldn't happen, whereas in reality this is entirely by design.
It wouldn't be a very effective CAPTCHA if you could repeatedly get it wrong then go back and try again; any bot could just start brute forcing it and learning from the experience.

PHP form validation on same page with external processing

I am trying to wrap up this contact/quote form which has same page validation but external processing. I have set up a variable to go in the form action and the variable/url changes from the same page to the processing page when the form validates. However, it is taking two clicks on the submit button to process the form after all the required fields have been filled in: All the required fields will be filled in, I click submit, the page reloads with the saved data variables and then when I hit submit agin, it finally goes through, sending the email and loading the thankyou page. I have searched the posts here and tried multiple things but have not found a solution. I am definitely not a php expert, still a newbie so this may not be the best way to accomplish this but I'd appreciate any ideas on how to finish this up. Here is what I have:
<?php
....
if (empty($Name) && empty($Company) && empty($Address1) && empty($City) && empty($State) && empty($Phone))
{
echo '<p class="tan">The fields marked with an * are required.</p>';
$Process = 'samepageurl';
}
/*else if (empty($Name) || is_numeric($Name))
{
echo '<p class="tan"><b>Please enter your name.</b></p>';
}*/
else if (empty($Company) || is_numeric($Company))
{
echo '<p class="tan"><b>Please enter your company name.</b></p>';
$Process = 'samepageurl';
}
else if (empty($Address1) || is_numeric($Address1))
{
echo '<p class="tan"><b>Please enter your address.</b></p>';
$Process = 'samepageurl';
}
else if (empty($City) || is_numeric($City))
{
echo '<p class="tan"><b>Please enter your city.</b></p>';
$Process = 'samepageurl';
}
else if (empty($State) || is_numeric($State))
{
echo '<p class="tan"><b>Please enter your state.</b></p>';
$Process = 'samepageurl';
}
else if (empty($Phone) || ctype_alpha($Phone))
{
echo '<p class="tan"><b>Please enter your phone number.</b></p>';
$Process = 'samepageurl';
}
else if (strlen($Phone) < 10 || strlen($Phone) > 12 || ctype_alpha($Phone) || ctype_space($Phone))
{
echo '<p class="tan"><b>Please enter a phone number with an area code.</b></p>';
$Process = 'samepageurl';
}
else if (isset($Name) && isset($Company) && isset($Address1) && isset($City) && isset($State) && isset($Phone))
{
$Process = 'processingurl';
}
?>
<form action="<?php echo $Process; ?>" method="post" class="print" >
<p><input type="hidden" name="recipient" value="responses#url.com"/>
<input type="hidden" name="subject" value="Web Site Response"/>
<input type="hidden" name="redirect" value="thankyou.html"/></p>
... form fields ...
</form>
Thank you in advance!
First check for missing variables, then extract and validate the variables, then serve content based on them.
<?php
function verifyPostContains(&$req) {
global $_POST;
$missing = array();
foreach($req as $var => $_) {
if(!isset($_POST[$var])) {
$missing[] = $var;
}
}
return $missing;
}
$requirements = array('name'=>'','city'=>'','state'=>'',...);
$missing = verifyPostContains($requirements);
if(count($missing)>0) {
$content = formErrorReport($missing);
sendHeaders();
echo $content;
exit();
}
// extract, making sure to sanitize
$name = sanitize($_POST["name"]);
...
$errorHtml = array();
// validate by reference. Effectively call testName($name).
if(failsValidation($name, "testName")) {
$errorHtml [] = generateError(NAME_ERROR, $name);
} else { $requirements["name"] = $name; }
if(failsValidation($city, "testCity")) {
$errorHtml [] = generateError(CITY_ERROR, $city);
} else { $requirements["city"] = $name; }
...
if(count($errorHTML)>0) {
generateErrorPage($requirements, $missing, $errorHTML);
} else { processForm($requirements); }
?>
this code assumes you have functions to do the various bits that need to be done, and has some string constants for generating error HTML.
As a newcomer you may want to google for some tutorials that explain doing form processing using PHP at the server, and JavaScript at the client. If you find a tutorial that gives you code that echos errors while it's testing the data, such as you code does, move along. It's not a good tutorial. If you find one that stops after it finds one error, move along too. If you find one that tells you to make sure the values are right in JavaScript, and then says "we already validated this at the client so we use the values directly in PHP", move along, too. Look for a tutorial that explains:
ensuring there's data in all the form fields, using JavaScript, so the submit button is disabled until there's data for all the fields.
ensuring the data matches your criteria, in PHP, so that people who just POST to your server without ever using your page don't get away with injecting all manner of fun stuff they weren't supposed to be able to do
you generate a page with all the errors explained, if there are any, and the form repopulated with the wrong data, but highlighted as wrong
you process the post request if there are no errors.
(Bonus points if the tutorial explains that a POST request is not required to actually ever generate page content as a response, other than a header that indicates whether or not the POST call was accepted or rejected.)

Flash/Php/MySQL Registration Form

I've been to almost every forum possible with this question (including this one). I almost got the answer to my question. The problem is no one seems to figure out my problem because everything looks right, and everything looks right to me too. Can someone please help me? Here are my codes.
Flash Code:
var lvSend:LoadVars = new LoadVars();
var lvReceive:LoadVars = new LoadVars();
register_button.onRelease = function(){
var valid:Boolean = validateForm();
if (valid) {
//gather information and put in loadvars object
lvSend.username = username1.text;
lvSend.password = password1.text;
lvSend.email = email1.text;
lvSend.sendAndLoad("register.php", lvReceive, "POST");
gotoAndStop(1);
}
};
lvReceive.onLoad = function(success:Boolean) {
if (success) {
username1.text = "";
password1.text = "";
email1.text = "";
}
}
function validateForm():Boolean {
if (username1.text == "" || password1.text == "" || email1.text == "") {
return false;
}
return true;
}
Php Code:
http://i.stack.imgur.com/RXPWb.png
(Sorry its in link form)
Please favorite this or something until I get an answer because I've been everywhere and no one could help me. :/ BTW I have been getting a few blank entries into my database but I don't know why. Also, the lvReceive function doesn't seem to work, but when I add the username1.text = ""; into the register_button function it seems to clear the text fields. Please help me. I left the database info on the php file cause I thought maybe the database I entered could be the problem, but I did use this php code with an html file and it worked fine. I will accept any answers. Thanks in advance! :D
lvSend.sendAndLoad("register.php", lvReceive, "POST");
You put the information in lvSend and not in lvReceive.
Perhaps you should put the information in lvReceive:
lvReceive.username = username1.text;
lvReceive.password = password1.text;
lvReceive.email = email1.text;
lvSend.sendAndLoad("register.php", lvReceive, "POST");

Categories