how to use $_POST to change some contents forever [duplicate] - javascript

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.

Related

Google reCaptcha v3 returns success as false

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.

Reading in Data from HTML Javascript form

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=

global variable not displayed in div

I declare a variable at the beginning of my .js file:
var option="blabla";
On page 1.html I click on a link to page 2.html where I have
<script>document.write(option);</script>
No text is displayed on 2.html. When I refresh the browser while I am on 2.html I get undefined as an output.
What do I have to do to have the text displayed straight after I click the link?
Alternatively, how can I get the following code work to output strUrl on 2.html:
on 1.html I have a link:
<a href="2.html" onclick="function1("item")">
on 2.html I have a div:
<div id="display">document.write(strUrl);</div>
then I have in my .js file:
function1(searchitem)
{
strUrl = 'http://blabla.com/'
+ '?key=' + searchitem;
}
You try to create a Javascript variable on a page and then use it on another page. This is a more-or-less broad problem, since you want to maintain values across pages. First of all, you need to decide where is this value going to be defined and where is it going to be used. If this is more like a server-side variable, then you need to define it on server-side and then generate it into your Javascript code. If you are using PHP, then you can do it like this:
<script type="text/javascript>
var foo = '<?php echo $bar; ?>';
</script>
Naturally, you need to initialize $bar to be able to do that. If the variable should be a client-side variable, then you need to use localStorage, like this on 1.html:
localStorage.setItem("option", "blablabla");
and then load it on 2.html:
localStorage.getItem("option");
Or, if you need to use it both on server-side and client-side, then you can use a cookie for this purpose. Using cookies i slightly more complex, but my answer to another question should get you going.
Let's focus on the cause this did not work for you. A Javascript variable will cease to exist when the page is unloaded, so you will not be able to use its value after that. So, you need to persist it somehow, storing it either on the server or the computer where the browser is being run.
As a side-note, I should mention that you can use Javascript variables accross pages if you load some pages inside iframes of a page, but that is a different scenario.
This is what FORMS and AJAX were invented for. If your server has a PHP processor (virtually ALL of them do), then you can rename your .html files to .php and use a bit of PHP to accomplish your goal.
A web page ending with .PHP works exactly the same as one ending in .html, except that you can now add snippets of PHP code where desired. It is not necessary to have any PHP code, but if you have some it can do stuff.
Method One: FORMs
If you want to switch to page2.html and see a value sent from page1.html, you can use a FORM construct and post the data from page1 to page2:
page1.php
<form action="2.html" method="post">
<input name="option" type="text" />
<input type="submit" name="sub" value="Go" />
</form>
page2.php
<?php
$p1 = $_POST['option'];
?>
<div>On page1 of this website, you typed: <?php echo $p1; ?>. That's what you did.</div>
Note how a <form> uses the name= attribute for the name of the variable that is sent to the other side.
Example Two: The AJAX method
HTML:
<div id=nonForm">
<input id="option" type="text" />
<input type="button" id="myButt" value="Go" />
</div>
<div id="results"></div>
jQuery:
$('#myButt').click(function(){
var opt = $('#option').val();
$.ajax({
type: 'post',
url: 'page2.php',
data: 'option='+opt,
success: function(john){
if (d.length) alert(john); //display result from Page2 in a pop-up box
$('#results').html(john); //Or, display it right on the page
}
});
});
PAGE2.PHP -- The AJAX processor file
<?php
$opt = $_POST['option'];
//Now, you can do something with the data in $opt, and then send back a result
$rtn = 'Hey, you sent: ' .$opt;
echo $rtn;
The primary (and most important) difference between the two methods is that the FORM will change pages on you. The user will be sent from Page1 to Page2, and the screen will flash as this happens.
What's exciting about AJAX is it sends data to Page2, where Page2 can do something with it (for example, a database lookup), and then Page2 sends different data back to Page1. This new data can then be displayed on the page WITHOUT the page refreshing.
Here are a couple of very basic AJAX examples, to get you going:
AJAX request callback using jQuery

Can I redirect to a new php file while posting a form input?

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?

Overwriting JavaScript variables to save permanently?

I'm creating a website with the option to Login with an administrative account and I want to be able to edit different elements in the HTML set to javascript variables. When you log in, there will be an input box to take a value from the user and apply it to a widget on the page. I haven't yet found a way to save the input value by overwriting the variable set for the widget and have it save to the webhost (GoDaddy) and stay throughout all sessions for anyone who shall be looking. I don't want to use Cookies or localStorage because I would like for the value to not only save on that user's session but all looking at the site. Ideas?
(EDITED CONTENT BELOW)
Alright, I've used a database. I've gotten the code below:
<html>
<head>
<title>
MyAccount
</title>
</head>
<body>
<center>
<h1>
Welcome to your account!
</h1>
<input name="alertVal" type="text" placeholder="Alert Value">
<input type="button" text="Save" onclick="<?php saveAlert()?>">
<?php
// Connects to your Database
function saveAlert(){
mysql_connect("My IP is here. Not sharing that.", "adminLog", "Yeah, not putting my pass on a forum...") or die(mysql_error());
mysql_select_db("adminLog") or die(mysql_error());
$data = mysql_query("SELECT * FROM Alert")
or die(mysql_error());
while($info == mysql_fetch_array( $data ))
{
mysql_query("Update Alert SET Value = '$cleanURL'")
INSERT INTO Alert (Value);
VALUES ($_GET['alertVal']);
}
}
?>
</center>
</body>
</html>
And that doesn't work. Raises a T_STRING error. I don't really understand that. Help?
I don't want to use Cookies or localStorage because I would like for
the value to not only save on that user's session but all looking at
the site. Ideas?
If you don't want to use the various client-side stores stored (such as cookies or localStorage) you might consider storing this information on the server, in a database or a file. Depending on the server side language you are using there might be different approaches to achieve that.
You should use some sort of a database or just a simple text file. If you don't want to use a database, I recommend using Yaml.
BTW all GoDaddy plans include MySql. you can use that.

Categories

Resources