PHP Posted Values deleting upon refresh - php

Why am I loosing all the form data whenever I refresh the page? I am posting data from previous page and using echo $_POST['test']; it displays everything once and when I refresh the page, nothing gets printed.
I also tried using sessions but sessions are also being overwritten while refreshing the page.
<?php
SESSION_START();
$_SESSION['coupons_count'] = $_POST['points'];
$_SESSION['dateofcoupon'] = $_POST['dateofcoupon'];
$_SESSION['timeofcoupon'] = $_POST['timeofcoupon'];
$_SESSION['points'] = $_POST['points'];
$_SESSION['storename'] = $_POST['storename'];
?>
<h2>Coupon Details</h2>
<form id="form1" method="post">
<span style="width:120px;"><strong>Restaurant:</strong></span> <?php echo $_SESSION['storename']; ?>
<strong>Date:</strong> <?php echo $_SESSION['dateofcoupon']; ?>
<strong>Start Time:</strong> <?php echo substr($_SESSION['timeofcoupon'], 0, -10); ?>
<strong>End Time:</strong> <?php echo substr($_SESSION['timeofcoupon'], 8, -2); ?>
<strong>Coupons:</strong> </php echo $_SESSION['points']; ?>

Your scenario:
1) Add empty values from $_POST (No error? Since there is indexes defined yet)
2) You send form data
3) Save $_POST variables back to session
4) Refresh of page / removes all $_POST variables
5) You assign again empty variables
So basically you have to check $_POST variables existence and only save than:
if (isset($_POST['points'])) {
$_SESSION['coupons_count'] = $_POST['points'];
}
// repeat for all variables

That's the right behavior for a web form. You have a form, you are filling in the values and posting it to itself, then if you will refresh the page, as you are NOT posting any values again so you get noting displayed.
If you want to keep the values persistent across multiple refreshes, then post the form to a separate page [easiest solution];
Like you can make a page formdata.php and post it to formaction.php.
add action tag in your form with action="formaction.php"
and then refresh the action page multiple times and you will see all variables persistent.

Finally, I ended up using in a weird manner.
if($_POST['points'] != null)
{
$_SESSION['coupons_count'] = $_POST['points'];
$_SESSION['dateofcoupon'] = $_POST['dateofcoupon'];
$_SESSION['timeofcoupon'] = $_POST['timeofcoupon'];
$_SESSION['points'] = $_POST['points'];
$_SESSION['storename'] = $_POST['storename'];
}
I know, this is not a professional way but I am looking for a quick tip to get rid of this issue.

I'm not sure what you are complaining about. If you don't POST the values again when you refresh your page (and your browser should ask you whether it should send the form again), you can't expect the $_POST to have any values in it.
Anyway, this might help you a bit:
$pairs = array(
"coupons_count" => "points",
"dateofcoupon" => "dateofcoupon",
"timeofcoupon" => "timeofcoupon",
"points" => "points",
"storename" => "storename",
);
foreach ($pairs as $sessionVar => $postVar) {
if (isset($_POST[$postVar])) $_SESSION[$sessionVar] = $_POST[$postVar];
}
Where the session variables will be overwritten ONLY IF there are corresponding $_POST values defined.

Related

Constant Variables in PHP after page reloads

im very new to PHP, so please excuse me if this is a stupid question.
So here is the scenario.
Im writing a PHP all in one page that gets a random word from an array, scrambles the word, then lets the user guess the word.
now im using the isset(), so it declares the variable, then once submit is clicked, it will get in user input via _POST().
Now the problem
I need the calculated variable to remain constant, but once the page reloads, it regenerates the variable.
is there anyway i can get pass this?
<?php
function GetShuffWord()
{
$arrayName = array('word1','word2','word3','word4','word5');
$randWordIndex = rand(0,4);
$randomWord = $arrayName[$randWordIndex];
$shuffledWord = str_shuffle($randomWord);
return $shuffledWord;
}
if(!isset($_POST['Submit']))
{
define("shuffledWord", GetShuffWord());
$tempWord = shuffledWord;
// showing the user shuffled word
echo " <h1 style='font-size: 50px' align = 'center'> {$tempWord}
</h1>";
}
else
{
$tempWord = shuffledWord;
echo " <h1 style='font-size: 50px' align = 'center'>{$tempWord} </h1>";
echo "else part";
}
?>
another problem is that if i declare the variable in the if, i cannot use variable in the else with out re-generating it.
You can just include the value as a hidden input field in your form.
<input type="hidden" name="myCalculatedValue" value="<?= $tempWord ?>" />
Then when the form is submitted you can just get it via $_POST['myCalculatedValue']
You can use session and put a check that if session has it already dont overwrite.
And when u want to overwrite you can do so as well by passing another flag to the script in your post request.

Possible to manipulate $_POST variable in php script and express it in another php script?

I've been trying to do form validation without using the url. So I thought that I would create a hidden field in my form and send it over to my validation php script. What I was hoping I would be able to do is set what ever errors there are in the form to this hidden field and return it. However once I get out of the scope it destroys whatever I set. I thought $_POST had global scope? Maybe I declared I set the hidden field wrong? I have placed the code below.
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/databaseConnect.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/functions.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/users.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/userDetails.php';
//get the refering url to be used to redirect
$refUrl = $_SERVER['HTTP_REFERER'];
if(isset($_POST['register'])){
//declare a temp error array
$tempError;
//check if the form is empty
if(empty($_POST['Email'])&&empty($_POST['Email Confirmation'])&&empty($_POST['Password'])&&empty($_POST['Password Confirmation'])
&&empty($_POST['Stage Name'])&&empty($_POST['Main Club'])){
$tempError = 'Please fill in the form.';
}else{
//set variables
}
if(!empty($tempError)){
//start a session to declare session errors
$_POST['errors'] = $tempError;
//redirect back to referring url
header('Location:'.$refUrl);
exit();
}else{
//log user in and redirect to member home page
}
}
Basic form (I excluded the input field as it would be really long)
<div class="col-md-6 well">
<span class="jsError"></span><?php if(isset($_POST['errors'])){ $errors = $_POST['errors']; } if(!empty($errors)){ echo '<p class="alert alert-danger text-center">'.$errors.'</p>'; } ?>
<form class="form-horizontal" role="form" method="post" action="controllers/registrationController.php" id="registration">
<input type="hidden" name="errors" value="<?php if(isset($_POST['errors'])){echo $_POST['errors']; } ?>">
</form>
I looked into using the $_SESSION variable method too but the stuff I found was either a bit complicated or it involved me starting a whole bunch of sessions everywhere (would make my code messy in my opinion).
$_POST is populated from the contents of the data passed by the browser to the server. When you send a Location header it causes the browser to load a new page, but since it will have no form data, nothing will be passed.
If you need to pass data from page to page then $_SESSION is the way to go. All that is required is a session_start() at the top of the pages that need access, and you can store your $_POST data like this:
$_SESSION['postdata'] = $_POST;
Retrieving it becomes
$email = $_SESSION['post']['Email'];
The alternative is to echo the data as a hidden <input> in a new form, but that will require a new form to be submitted and I get the feeling you want something seamless.
Note also that $_SERVER['HTTP_REFERER'] is not guaranteed to be accurate, or even present. You shouldn't rely on this for production code. It might work for you with your browser in your test set-up, but that's no guarantee it'll work for other browsers. Find another way.
You can achieve this by using javascript instead of a redirect, but the only way to pass data through a redirect is via the URL, the session, or cookies.
$_POST['errors'] = $tempError;
//redirect back to referring url
?>
<html><head><title></title></head><body>
<form id="temp_form">
<?php
foreach($_POST as $k=>$v) {
?><input type="hidden" name="<?php echo htmlentities($k); ?>" value="<?php echo htmlentities($v); ?>" /><?php
}
?>
</form>
<script type="text/javascript">
setTimeout(function() { document.getElementById('temp_form').submit(); },100);
</script>
</body>
</html>
<?php
die();

How to get post values from first page to third page ,as post

i have 3 pages
Page1.php,page2.php,page3.php
In page1.php, i have some hidden values, for example 'name'
After the submission of page1.php, it will go to page2.
Then after some process in page2.php, it should need to automatically submit to page3.php(where page3.php is in another sever)
Finally,when i print the $_POST variables in page3.php, i need to get the variable 'name'
you could stick it in the session
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
or you could pass them in hidden vars on page2.php if it has a form...
You will want to look into sessions.
If you need them in POST, try this:
$display = "";
$saveFields = array('one', 'two'); // whitelist of fields to add to the form hidden
foreach ($_POST as $key => $val) {
if (!empty($val) && in_array($key, $saveFields))
$display .= '<input type="hidden" name="'.$key.'" value="'.$val.'" />';
}
echo $display;
Should get you where you want to go. The whitelist just ensure's that random stuff is not injected that does not need to be.
(1) Option is to add hidden input on page2 too.
(2) Option is to set the value from page1's name into session and use it on page3
There are several solutions:
PHP sessions
cookies
passing arguments as GET/POST parameters
storing data in database
In simple cases passing arguments as GET parameter page2.php?name=... or using hidden form field is the best solution
This seems straightforward to me, page one has a hidden value called name. Page 2 should retrieve the post $_POST['name'] and print it on page 2 as a hidden field. Once you post it to Page 3 you can retrieve it the same way $_POST['name'].
Realistically if the data is exactly the same and is being carried all the way to page 3, why do you even need it? Can you not just declare it on page 3?
Okay, the way I read this is that on your first page you have a UI with a form. The form is then submitted for processing to page 2. After processing is done, you want to redirect, if you will, the user to another site (or server, doesn't necessarily have to make a difference).
If I got that right, here is what you should do; instead of using the header(); function (php), print an empty page with a hidden form with all of the details you want to send over and use javascript to emulate the user 'submitting' the form.
< div style="display: none;">
< form action="https://mywebpage.com/myscript.php" method=POST>
< input type=hidden name="key_1" value="value_1">
< input type=hidden name="key_2" value="value_2">
< input type=hidden name="key_3" value="value_3">
< input type=submit id="formButton" style="visibility: hidden; ">
< script language="javascript">
document.getElementById("formButton").click()
< /form>
< /div>

How to keep all the POST information while redirecting in PHP?

header('Location: ' . $uri);
This will miss all the $_POST information.
Don't use $_SESSION as you have been suggested. Session data is shared with all other pages, including the ones open in other tabs. You may get unpredictable behaviour if you use the same trick in multiple places of your website.
An untested better code would be something like this.
session_start();
$data_id = md5( time().microtime().rand(0,100) );
$_SESSION["POSTDATA_$data_id"] = $_POST;
header('Location: ' . $uri."?data_id=$data_id");
In the next page you may retrieve the previous post like this
session_start();
$post = array();
$data_key = 'POSTDATA_'.$_GET['data_id'];
if ( !empty ( $_GET['data_id'] ) && !empty( $_SESSION[$data_key] ))
{
$post = $_SESSION[$data_key];
unset ( $_SESSION[$data_key] );
}
The code above is not tested, you may have to deal with some error before it works.
if u want to carry forward your POST data to another pages ( except the action page) then use
session_start();
$_SESSION['post_data'] = $_POST;
Indeed, you can't redirect POST requests.
Either let your server proxy the request (i.e. make a cURL request to the other site) or create another form, fill it with hidden fields and submit it with Javascript/let the user click.
Alternatively, as #diEcho says, depending on what you're trying to do: sessions.
If you perform a redirect the post will be lost and a GET will occur.
You could save your POST in a SESSION or encode it in the GET (as query string)
You could save the post data in the session, redirect, and then retrieve it back from the session.
session_start();
$_SESSION['POSTDATA'] = $_POST;
header('Location: ' . $uri);
Then in the PHP file for the new location, retrieve the post data like this:
$_POST = $_SESSION['POSTDATA'];
I do use my own simple method.
Just think very logical! For example if you use a text attribute which you want to keep the value of, you can use:
<?php $textvalue = $_POST['textname']; ?>
<input type="text" name="textname" value="<?php echo $textvalue; ?>" />
<br />
//And if you want to use this method for a radio button, you can use:
<?php if(isset($_POST['radio1']){
$selected = "selected";
} ?>
<input type="radio" name="radio1" <?php echo $selected; ?> />

PHP quiz send data to next page

ok, i'm trying to do a quiz...all good by now. but when i'm trying to send the collected data(radio buttons values) through pages i can't get the logic flow. I have the main idea but i can;t put it into practice.
i want to collect all radio values
create an array containing this values
serialize the array
put the serialized array into a hidden input
the problem is that i want to send data on the same page via $_SERVER['PHP_SELF'] and i don;t know when in time to do those things.(cause on "first" page of the quiz i have nothing to receive, then on the "next" page i receive the S_POST['radio_names'] and just after the second page i can get that hidden input). i hope i made myself understood (it's hard even for me to understand what my question is :D )
You could try to use the $_SESSION object instead... For each page of your quiz, store up the results in the $_SESSION array. On the summary page, use this to show your results.
To accomplish this, on the beginning of each page, you could put something like:
<?
session_start();
foreach ($_POST as $name => $resp) {
$_SESSION['responses'][name] = $resp;
}
?>
Then, on the last page, you can loop through all results:
<?
session_start();
foreach ($_SESSION['responses'] as $name => $resp) {
// validate response ($resp) for input ($name)
}
?>
Name your form fields like this:
<input type="radio" name="quiz[page1][question1]" value="something"/>
...
<input type="hidden" name="quizdata" value="<?PHP serialize($quizdata); ?>"/>
Then when you process:
<?PHP
//if hidden field was passed, grab it.
if (! empty($_POST['quizdata'])){
$quizdata = unserialize($_POST['quizdata']);
}
// if $quizdata isn't an array, initialize it.
if (! is_array($quizdata)){
$quizdata = array();
}
// if there's new question data in post, merge it into quizdata
if (! empty($_POST)){
$quizdata = array_merge($quizdata,$_POST['quiz']);
}
//then output your html fields (as seen above)
As another approach, you could add a field to each "page" and track where you are. Then, in the handler at the top of the page, you would know what input is valid:
<?
if (isset($_POST['page'])) {
$last_page = $_POST['page'];
$current_page = $last_page + 1;
process_page_data($last_page);
} else {
$current_page = 1;
}
?>
... later on the page ...
<? display_page_data($current_page); ?>
<input type="hidden" name="page" value="<?= $current_page ?>" />
In this example, process_page_data($page) would handle reading all the input data necessary for the given page number and display_page_data($page) would show the user the valid questions for the given page number.
You could expand this further and create classes to represent pages, but this might give you an idea of where to start. Using this approach allows you to keep all the data handling in the same PHP script, and makes the data available to other functions in the same script.
You want to use a flow such as
if (isset $_POST){
//do the data processing and such
}
else {
/show entry form
}
That's the most straight forward way I know of to stay on the same page and accept for data.

Categories