How to validate reCAPTCHA - php

I want to write a JavaScript and php validation for reCAPTCHA In my php I have the function below but I doesn't work. It doesn't, return an errror message if I enter the wrong reCAPTCHA code:
function invalid($inputname,$error_message)
{
$this->js.='if (!invalid(formname.'.$inputname.',"'.$error_message.'")) return false;';
if ( isset($_POST[$inputname]) && strlen($_POST[$inputname]) - strlen(str_replace(' ','',$_POST[$inputname])) > $limit && $_POST[$inputname] != "")
{
$this -> error_message .= $error_message.'<br>';
}
}
I don't want to just echo the message I want to echo the message on top of the form like I did with my other validate using:
Can someone show me how to do it correctly in php and javascript?
Thanks

Please read the reCAPTCHA documentation. It clearly outlines the correct use of the recaptcha_check_answer() function (part of the reCAPTCHA PHP library) to validate solutions.

This
strlen($_POST[$inputname]) - strlen(str_replace(' ','',$_POST[$inputname])) > $limit
will be false, assuming $limit is something like 6. Should be just
strlen(str_replace(' ','',$_POST[$inputname])) > $limit
Let's say the captcha is "bananas". strlen("bananas") - strlen("bananas") == 0.
Added The JavaScript doesn't return false at any point, so it will return undefined if the captcha is correct, which may affect your code elsewhere (particularly if you are using === ).

Related

how to get a post or get variable

I have an html form that depending on the checkbox my java-script change it from GET to POST. This piece of code is currently working.
My question is I have a variable on the server side that I need to get. The html variable is sent either as POST or GET, but not sure how to retrieve that variable regardless or what method the html uses. I know how to get the variable as either POST or GET manually, but Not sure how to go about accomplishing this automatically. Any suggestions?
$myVariable = $_GET['htmlVariable'] or $myVariable = $_POST['htmlVariable']
1) Use $_GET if you know that data is coming via URL parameter
if (isset($_GET['htmlVariable'] && $_GET['htmlVariable'] != '') {
$htmlVariable = $_GET['htmlVariable'];
}
2) Use $_POST if you know that data is coming via HTTP POST method
if (isset($_POST['htmlVariable'] && $_POST['htmlVariable'] != '') {
$htmlVariable = $_GET['htmlVariable'];
}
3) If you don't know use $_REQUEST
if (isset($_REQUEST['htmlVariable'] && $_REQUEST['htmlVariable'] != '') {
$htmlVariable = $_GET['htmlVariable'];
}
It sounds like you're looking to check if one of the two methods is found. If it is, use that method, and if not, use the other method. To achieve this you can use isset(), and note that you'll also want to check that the string isn't empty:
if (isset($_GET['htmlVariable'] && $_GET['htmlVariable'] != '') {
$myVariable = $_GET['htmlVariable'];
}
else if (isset($_POST['htmlVariable'] && $_POST['htmlVariable'] != '') {
$myVariable = $_POST['htmlVariable'];
}
else {
$myVariable = 'something else';
}
Also note that the order in which you check for the methods may make a difference, depending on your logic.

Redirection with $_SERVER["PHP_SELF"] and using header()

is it possible to do this , im trying to validate a form then, it will redirect using header() if TRUE.. but it seems not to be working? or my method is completely wrong ?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST["clientEmail"];
if ($email != $sentEmailClients) {
echo 'Please enter a valid email';
} else {
$newURL = "http://www.myurl.com";
header('Location: ' . $newURL);
}
}
Give us more details about what actually happens when you run your code. You're likely facing one of the following problems:
You're using header() after you've already sent output to the browser. Headers must be sent before any other output. Check out the docs. If you change that line with die('redirecting') and that text shows up, then this is your problem.
Request method is not POST. Add die($_SERVER['REQUEST_METHOD']). If something other than POST is printed, then this is your problem.
$_POST['clientEmail'] is not set, or is not equal to $email
$email is not what you expect (where does it come from?)
$sentEmailClients is not what you expect (where does it come from?)
Basically, "why doesn't it work?" is not a good question because it doesn't give us much info with which to help you. Be more specific about what is happening.
Show enough of your code that we understand the origin of the variables you use.
Hi It seems that Your outermost if condition is not working thats why your header function is not working i just tried this and it woks fine. That means either your first if condition is false or either second if condition becomes true every time just try to echo your values before checking them.
<?php
if (1) {
$email = $_POST["clientEmail"];
if (0) {
echo 'Please enter a valid email';
} else {
$newURL = "http://www.google.com";
header('Location: ' . $newURL);
}
}
check this print_r($_SERVER["REQUEST_METHOD"]); is POST or not and
$email != $sentEmailClients true or false

Php Filter array

I need a simple example of php filter array. This function is new for me so please I can't understand complex program of it.
I want to store filtered data to the database from a simple form where these conditions can exist.
i.e:
NAME in capital words.
proper email/Password syntax.
proper address and mobile number (1234-1234567)
registration no: 2012-2015-AUP-1234
if any one mistakes an alert or message is displayed.
array_filter :
The official documentation for PHP is full of very understandable examples for each function. These examples are given by the documentation or the community, and follows each function description.
PHP Documentation
Form validation :
A little code example for the script called by your POST form. Of course a lot of changes to this can be made to display the errors the way you like, and perhaps tune more precise checks on each data.
<?php
if (isset($_POST['name']) && !ctype_upper($_POST['name'])) {
$errors[] = 'name should be uppercase';
}
if (isset($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'email is invalid';
}
if (isset($_POST['password']) && strlen($_POST['password']) >= 6 && strlen($_POST['password']) <= 16)) {
$errors[] = 'password should be between 6 and 16 characters length';
}
if (isset($errors)) {
// do not validate form
echo '<ul><li>' . join('</li><li>', $errors) . '</li></ul>';
// ... include the html code of your form here
}
else {
// ... call things that must work on validated forms only here
}

Javascript prompt() output to PHP function

I've been trying to get user input from a Javascript prompt into a PHP function and have run into a lot a walls doing so. I am at a loss trying jQuery's $.post method- as the PHP simply does not want to execute, not sure why.
Anyways, here is a gist of what I am doing at the moment:
1 A project and its data are loaded from a database- this info is displayed in a table.
2 All data in the table is editable via Javascript prompt(), the code I am using for this is below:
<div id="lvl3"><?php echo $fetchdata['name']; ?></div>
The above work as such: lvl3 is a tag for font styling; blank href to make it act as a link; popupprompt is the prompt function I made, it takes one argument, the 'type' or what is being edited (1 for project name, 2 for project description, ect); return false so the page doesn't reload; php echo to display project data in the table.
3 Once the user clicks the object above- it executes a javascript function called popupprompt taking an argument of 'type', or what project info is being changed. the code for this function is below:
function popupprompt(type) {
switch(type)
{
case 1:
var name = prompt("Project Name:", "");
if (name != null && name != "")
{
//Change Project Name
var getname = name;
var gettype = type;
$.post("edit.php", { type: gettype, name: getname });
} else if (name == "") {
senderror("Please enter a valid Project Name");
} else {
//Prompt canceled
sendnotification('Canceled my ass!');
}
break;
case 2:
//Description?
case 3:
//Version?
case 4:
//Release?
default:
alert("There was an error processing your request.");
break;
} }
Th issue I am having in this function is that nothing in edit.php is executed- and i haven't the slightest clue why. Also, i've had to change the brackets around so it shows properly in the code box- so don't mind those.
4 Anyways, now user input is posted to edit.php- which doesn't work, but i'll post it anyways:
<?php
$type = $_POST['type'];
$name = $_POST['name'];
switch($type) {
case 1:
dbconnect();
$urlext = geturlext();
$authenticated = isauthenticated();
if ($authenticated == false)
{
echo("<script>senderror('Access denied');</script>");
} else {
//Escape and trim input
$input = trim($input);
$input = mysql_real_escape_string($input);
$update = "UPDATE 'projects' SET 'name' = '$input' WHERE 'name' = '$urlext'";
$updatequery = mysql_query($update) or die(mysql_error());
echo("<script>sendnotification('Project Name updated');</script>");
}
break;
default:
break;
}
?>
Again had to move some brackets around. But anyways- this function is supposed to update the data in the database- however, it instead does nothing. I've placed alerts in the beginning and they are never called.
Anyways, long story short- if you know what i'm doing wrong please enlighten me, also, if there is a better way to do this- please let me know!
I appreciate all help,
Thanks
Figured it out after a good week of setting it aside. Took a long look at it in firebug, rooted out a typo that was causing most of my issues and also a MySQL syntax error.
I don't know why, but my custom error reporting system does not work when called from a file in this manner. It might be another thing i'm overlooking but firebug sure helped.
Thanks to those who tried to help <3

Hiding a div upon login with php

I am trying to hide a div once a user has logged into there account of my online store (built with cartweaver 4 php) but i just cant seem to get it to work.
the php code for defining wether the user is logged in or not is as followed:
if(!strlen($_SESSION["cwclient"]["cwCustomerID"]) ||
$_SESSION["cwclient"]["cwCustomerID"] === 0 ||
$_SESSION["cwclient"]["cwCustomerID"] === "0" ||
$_SESSION["cwclient"]["cwCustomerType"] == 0 ||
(isset($_SESSION["cwclient"]["cwCustomerCheckout"]) &&
strtolower($_SESSION["cwclient"]["cwCustomerCheckout"]) == "guest"))
and the div i would like to hide upon login, which contains a table, have been given an id and class of:
<div id="newcustomertable" class='newcustomer'>
I have tried applying this method using css: Show Hide div if, if statement is true
but that ended up giving me an undefined variable error on my testing server.
I admit i am a bit of a php newbie, so if anyone who is able to make more sense of this could help out and possibly find a solution it would be much appreciated.
Thank you.
<div id ="newcustomertable"></div>
<?
if(!isset($_SESSION["cwclient"]["cwCustomerID"]) ||
!strlen(#$_SESSION["cwclient"]["cwCustomerID"]) ||
#$_SESSION["cwclient"]["cwCustomerID"] === 0 ||
#$_SESSION["cwclient"]["cwCustomerType"] == 0 ||
(isset($_SESSION["cwclient"]["cwCustomerCheckout"]) &&
strtolower(#$_SESSION["cwclient"]["cwCustomerCheckout"]) == "guest"))
{
?>
<script>
document.getElementById("newcustomertable").style.display = "none";
</script>
<?
}
?>
Make sure that the condition check is AFTER the div element getting rendered. Because if you put it before the element the page would not have fully rendered and so the script will not be able to get the div that you want to hide.
REVERSE Condition based on OP's request. I know this is a kluge, folks. Dont flame me!
<div id ="newcustomertable"></div>
<?
if(!isset($_SESSION["cwclient"]["cwCustomerID"]) ||
!strlen(#$_SESSION["cwclient"]["cwCustomerID"]) ||
#$_SESSION["cwclient"]["cwCustomerID"] === 0 ||
#$_SESSION["cwclient"]["cwCustomerType"] == 0 ||
(isset($_SESSION["cwclient"]["cwCustomerCheckout"]) &&
strtolower(#$_SESSION["cwclient"]["cwCustomerCheckout"]) == "guest"))
{
//do nothing
}
else
{
?>
<script>
document.getElementById("newcustomertable").style.display = "none";
</script>
<?
}
?>
You've got at least 3 variables there that could be throwing your undefined variable warning:
$_SESSION["cwclient"]
$_SESSION["cwclient"]["cwCustomerID"]
$_SESSION["cwclient"]["cwCustomerType"]
you need to isset() each of those before doing any tests.
For starters, the strlen function in PHP returns an INT, not a boolean.
Change from:
(!strlen($_SESSION["cwclient"]["cwCustomerID"])
to:
(strlen($_SESSION["cwclient"]["cwCustomerID"]) > 0)
First of all could that not just be simplified to the following if statement to make it easier
if (($_SESSION["cwclient"]["cwCustomerID"]<>NULL)&&($_SESSION["cwclient"]["cwCustomerCheckout"]) == "guest")) {
#code here
}
Second of all to hide the div if they are logged in you could do it like this
if (($_SESSION["cwclient"]["cwCustomerID"]<>NULL)&&($_SESSION["cwclient"]["cwCustomerCheckout"]) == "guest")) {
$shouldhide="style='visibility:hidden;'";
} else {
$shouldhide="";
}
echo"<div id='hidethis' $shouldhide>";
Although if the content is a security risk it'd be better to not output it at all as it's still visible in the source code.

Categories