I am testing my user login/registration system. I finally finished the form and I have been testing the form for a while now. It was working before I got the form finished and it works perfectly fine on another page however, it won't work on my page for registration. It keeps sending the success as false. My other page is a contact form and it's not that different from my registration page. It has all the same files inside.
My error code keeps showing me that I'm a bot when I'm clearly not a bot and I'm just testing out my own code.
I thought before there was a problem with where the code was stored in the directory at first, so I tried that.
Then, I thought that if I changed the keys, then maybe I would manage to get the system to work again. That didn't work.
Finally, I tried rearranging my html code to get it to work and that didn't work either.
Now, the crazy part, I'm still getting a score of 0.9 (checked on recaptcha site), which is enough for me to pass as a human but, it's still giving me that error within the JSON.
It worked fine before but, as soon as I started to test my input validation for my registration form, it began to call my response a false.
This is the error I keep getting. I wasn't too sure about formatting a JSON. This was returned with the php function var_dump. It was technically just one line.
object(stdClass)#13 (2)
{
["success"]=> bool(false)
["error-codes"]=> array(1)
{
[0]=> string(22) "missing-input-response"
}
}
This is the script I have in a file called recaptcha.php
<script src='https://www.google.com/recaptcha/api.js?render=<?php echo SITE_KEY; ?>'></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('<?php echo SITE_KEY; ?>', {action: 'homepage'}).then(function(token) {
document.getElementById('g-recaptcha-response').value=token;
});
});
</script>
EDIT/
Added some additional code.
A php function. The constant SECRET_KEY is defined as a global variable in another file.
function getCaptcha($secretKey) {
$response =
file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . SECRET_KEY . "&response={$secretKey}");
$reCaptcha = json_decode($response);
return $reCaptcha;
}
This is included where I verify the recaptcha.
$reCaptcha = getCaptcha($_REQUEST['g-recaptcha-response']);
var_dump($reCaptcha);
If that helps.
I'm expecting it to turn into ["success"]=> bool(true) but, I don't even have the slightest clue what's wrong. I'm ready to get Google on the phone just to solve this issue. Can anyone help?
This error means that you're not passing in the site 'secret' param to the POST request to:
https://www.google.com/recaptcha/api/siteverify
Check that the 'secret' param (called SECRET KEY in the settings screen of the admin area), is correct and is being sent in the POST request.
Okay, so after looking at a few things, I found out why it kept returning as a "missing-input" error.
I had a page with two forms and only one recaptcha.
<form>
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" />
</form>
<form>
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" />
</form>
Because there were two of them, the API didn't know which to distinguish and instead of assigning the same value to both, it assigned no value to either. So, in-order to fix this I changed my javascript to this:
<script src='https://www.google.com/recaptcha/api.js?render=<?php echo SITE_KEY; ?>'></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('<?php echo SITE_KEY; ?>', {action: 'homepage'}).then(function(token) {
document.getElementById('g-recaptcha-response').value=token;
document.getElementById('g-recaptcha-response2').value=token;
});
});
</script>
And my input form looked something like this:
<form>
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" />
</form>
<form>
<input type="hidden" id="g-recaptcha-response2" name="g-recaptcha-response2" />
</form>
The same value but, put into two separate fields. Even if you are using the second field for just one page, it's okay to leave it in there because it won't affect a page with just one recaptcha. As long as the first field is used to store the token and is reference in your html. I also changed this in the php.
$reCaptcha = getCaptcha($_REQUEST['g-recaptcha-response2']);
var_dump($reCaptcha);
I guess for anyone building a page with multiple forms, if you want to use recaptcha, you will need to distinguish two different input fields to receive the token. After spending nearly a day on this, I can't believe it took me that long to figure out something so simple. This will solve the missing-input error as well as the invalid-input error.
Related
This question already has an answer here:
Once I refresh the page that is getting data through a form , every thing will be gone
(1 answer)
Closed 10 months ago.
I am trying to populate data from a website to another wensite:
a.html:
<form action="b.php" method="post">
<textarea id="myProjects" name="mp"></textarea>
<input id="submit" type="submit" value="Submit" />
</form>
in b.php:
<?php $content=$_POST['mp'];
echo "you entered ".$content;
?>
This works in a very strange way, when I click submit button, I am directed to the b.php page, and I can see what I entered. But if I reload this page, not refresh, my contents disappear, and throwWarning: Undefined array key "mp" It looks like data received from $_POST is "temporarily" stored. I am new to PHP, so I am not sure how can I figure it out.
You can use the PHP SESSION feature to keep the data persistent:
in b.php:
<?php
// Start the session
session_start();
// save the input var as a SESSION property
if (isset($_POST['mp'])) {
$_SESSION['content'] = $_POST['mp'];
}
// display the property
echo "you entered " . $_SESSION['content'];
Generally speaking, what you want to do is to store the value of $_POST['mp'] into the $_SESSION variable so that it persists from one page request to the next.
However doing it by manipulating these variables directly is generally bad practice. Unless you sanitize the user input you are open to a myriad of scripting attacks. Although there is some learning involved, you are much better off using an established PHP framework (for example Laravel), which has a full set of validation functions, and manages the process of starting the session for you. A good framework will also help you in many other ways.
I have a todo list program and I want it to be reset to a predefined set of json within the json file once a button is clicked. For example, if the json file was full with data and someone clicked the button I want it to edit the json file to just say:
[{"completed":false,"task":"Kitchen - Sweep Floor","important":false}]
This is on cpanel latest using the latest stable php version. I've tried fwrite and file_put_contents but can't seem to get it working.
This is what I've tried already:
<html>
<h2>Click</h2>
<form action="" method="post">
<button name="click" class="click">Click me!</button>
</form>
<?php
if(isset($_POST['click']))
{
echo file_put_contents("test.json","[{"completed":false,"task":"Kitchen - Sweep Floor","important":false}]");
}
?>
</html>
When clicking the button nothing happens, no errors or anything?
You haven't assigned an action to the form, for this to work you should add the URL of the current page (so it redirects to itsself). Only then the post request is sent.
PHP won't run anything asynchronous: stuff only happens on page load.
You have syntax errors in your script - you have to escape the quotes in the string. Always look at the webserver error log or enable error display during development.
Here is the fixed code:
echo file_put_contents("test.json","[{\"completed\":false,\"task\":\"Kitchen - Sweep Floor\",\"important\":false}]");
You should use something like json_decode. Don't build json by hand:
$data = array(
"completed"=>false,
"task"=>"Kitchen - Sweep Floor",
"important"=>false
);
echo file_put_contents("test.json",json_encode($data));
I am creating a website backed by a database. I have created my forms that collect the information but now i need to read in the input from the form when user clicks submit and process it for mySQL. I am having my form action be a new page but I can't figure out how to read in value from the previous page. My Form code looks like this:
<div data-wrapper-react="true">
<span class="form-sub-label-container" style="vertical-align:top;">
<input type="text" id="first_3" name="q3_fullName3[first]" class="form-textbox validate[required]" size="10" value="" data-component="first" />
<label class="form-sub-label" for="first_3" id="sublabel_first" style="min-height:13px;"> First Name </label>
</span>
When user hits submit the action for this page is connect.php. I am not sure how to read in the value there. I tried this following command:
document.getElementById("first_3").value;
This just displays the code on blank html page for connect.php and not read in the values. The data from the forms needs to be processed into different tables if someone can help with that as well that would be great. Thanks
Form handling, in the way you are describing, is something you do server-side. PHP is handled on the server first where PHP tags can be evaluated to HTML, then this is returned to the browser. You would not handle form input from javascript, until after your PHP has done something with it. Here is a refresher: https://www.w3schools.com/php/php_forms.asp
<?php echo $_POST["q3_fullName3[first]"]; ?> would output the value into the HTML page allowing you to do something like this:
console.log("<?php echo $_POST["q3_fullName3[first]"]; ?>");
If you view source of the HTML, you will notice the PHP tag is gone and replaced with the form field value.
It sounds like you might want to get a book about PHP + MySQL since interacting with a database is a more advanced topic. I can recommend this one:
https://www.amazon.com/Learning-PHP-MySQL-JavaScript-Javascript-ebook/dp/B00QUBHNFI/ref=mt_kindle?_encoding=UTF8&me=
I have a html web page which I use to get some user input. This input is then posted using jquery to a php script which in turn sends a get request to a REST API to receive json data.
My question really is: is it possible to change my php file into another webpage with embedded php and redirect to this while posting the variables to the same script, so I could display the json results in a table on a new page simultaneously.
I already receive the json in the javascript file and I know I could use this to create a table, I was just interested if I could in fact do it all in one go on the php page as I already have script written to populate a table using the json data.
I have included some basic fragments of my code to help explain what I am doing.
HTML:
<head>
<script type="text/javascript" src="collect_User_Input.js"></script>
</head>
<p> What is the unique id of the beacon? </p>
<form> <input type="text" id="uniqueId" /> </form>
<button onclick="collect_User_Input();" >Send Request</button>
JS:
var uniqueId = document.getElementById('uniqueId');
$.post("send_Request.php", { uniqueId: uniqueId.value },function(result) {
alert(result);
PHP:
$uniqueId = $_POST["uniqueId"];
(GET request using curl)
echo ($uniqueId);
I tried skipping the javascript step and submitting the form directly, but this always gave me forbidden error messages. as you may have guessed I am very new to this so any advice is welcome.
In your PHP you will most likely want to return some JSON using json_encode:
http://php.net/manual/en/function.json-encode.php
Within your JSON, you could return a success value - then depending on the value of that you can redirect using:
window.location
You could even have a second attribute that returns what page you want the user redirected to if it isn't the same as the uniqueID:
{"success":true,"location":"/your/path/here.html"}
The flip side being, if there is an error you can return this to your page with a relevant message:
{"success":false,"message":"ID not found"}
I use this process to check something is valid on the server before doing the redirect, which sounds more or less the same as what you want to do?
I have 2 php files "source.php" and "target.php". In the source.php part I have,
<form method="POST" id="form1" action="target.php">
...
<input type="submit" name="submit" value="Submit"/>
</form>
When I click on submit it goes to the "target.php" (even if I have errors in the form), but I want that, only after all form fields are validated it will go to the target page, else it shows some kind of warning message and stays on the same page. Please help! Maybe this is a stupid question for some but I am a beginner. (I know how to do all the field validations and its working fine).
Duplicate of duplicate questions.Please search throughly before you post next time.
Generally javascripts are used for validation.But there are cases when javascripts become inefficient,for example when you need to validate country and its states.Its not practical to send the entire list of countries and states to the client. In such scenarios AJAX is used.By using AJAX the client sends the data to server immediatly after the user enters it.then it fetch only the required data.Its a simultaneous two way communication between client and server.for example if the user enters country name as INDIA,using AJAX states of INDIA are loaded for validation,thus saving bandwidth.
JavaScript and AJAX are not easy to learn,you must research try and correct different codes.Just google "JavaScript form validation"...
This is from w3Schools...
Required Fields
The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
The function above could be called when a form is submitted:
Example
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
here is more basic examples http://www.w3schools.com/js/js_form_validation.asp
Good Luck
You can use AJAX to validate your form. JavaScript is not recommended for form validation.
A simple tutorial for AJAX Validation is available here
But be aware, even if you are validating your form before submission to target.php, always make sure that you check the data in target.php too. This is because JavaScript can be changed (thanks to the modern DOM interpreters) in the browser. It can be made so that the form is submitted without AJAX verification. So you should check it twice, before and after submission.
Also make sure to escape the data, as user input can never be trusted.
You should also user strip_tags($string) to prevent use from inserting php code.
JavaScript is most likely the easiest way to do this (read the other posts).
However, if you don't want to use JavaScript you could always check if all forms are set using isset() or something similar and then passing on the $_POST variables in the URL and grabbing those using $_GET. Of course make sure there isn't any sensitive information in the URL. In addition: you could always work with global variables.
Another way to do this without JavaScript is submit to a database after several checks (like escaping the strings etc.), perhaps even encrypt, but I don't suggest this since this is the long way around.