Preserve $_POST variables through different pages like $_SESSION - php

Once some data are submitted through POST, is it possible to make them available as $_POST through different pages, same like how $_SESSION allows us to do?

You'll need to parse the data in $_POST and recreate it in your form. You can do it with hidden fields.
Or, you can save the $_POST data in a user session and refer to it when you need it. You'll have to manage the lifecycle of the data to make sure it doesn't stay around too long.

Digging up an old question today. But i forgot to post the working solution I dug....
Place this snippet in top of your every page
if(isset($_POST) & count($_POST)) { $_SESSION['post'] = $_POST; }
if(isset($_SESSION['post']) && count($_SESSION['post'])) { $_POST = $_SESSION['post']; }

The problem is that you are sending the data in via the URL which is stored in the $_GET variable, not in $_POST. If you want the ability to submit the data in either format, use $_REQUEST instead.
There is a bit of a debate on whether it is a good idea to use $_REQUEST, but if you are doing a simple site, there is little wrong with it.
If you would rather not use $_REQUEST, then you can use the following code on each variable you are expecting:
if (!empty($_GET['foo'])) {
$foo = $_GET['foo'];
} elseif (!empty($_POST['foo'])) {
$foo = $_POST['foo'];
} else {
die("Foo not submitted");
}

Related

PHP _POST Array

I am wondering why: without clicking the submit button on a form on my PHP page, the _POST variable is already set.
For example, I have this piece of code on the web page:
if (isset($_POST)){
echo "XXXXXXX";
}
It turns out the XXXXXX is echoed just when the page loads the very first time -- at this point I have of course not submitted any data to the server using POST. Why would this be the case?
As specified on PHP.net, it is automatically created.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.
To address your code, it is created, but it's empty.
To better test if the user has made a POST request, simply test for an index on $_POST, like isset($_POST['someFieldName'])
Your code should test if it's empty or not:
if(!empty($_POST)){
echo "a";
}
or
if(isset($_POST['someFieldName'])){
echo "a";
}
$_POST is a superglobal array and it is always set. If you do not pass any value to it using post method it will be empty. So set a value to this array and check whether that value is available or not like this:
if(isset($_POST['submit'])){
//Do this...
}
The same is true for the $_GET superglobal. These are always set regardless of HTTP Method. You can check if a request was a POST, GET, PUT, etc by checking the REQUEST_METHOD
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// this was an HTTP POST request
}
Check if the variable is empty or not. $_POST will always be set.
So something like the following should work:
if(!empty($_POST['textFieldName'])){
echo "XXXXXXX";
}
$_POST is superglobal and it's always set as an empty array.
Try this, just to understand better:
if(!is_null($_POST))
{
print_r($_POST);
}
Why is this going to help you to understand? - Because isset checking if a variable is set and is not NULL.

Save Constant GET Variable In A Session

Can some explain to me the best way to store a $_GET variable in a session and the only way the sessions changes is when we verify the data the session is being change to is different from the GET variable.
Currently i have
$tid = clean_get($_GET['tid']);
in a global file which is included on every page the problem with that is the value of $tid will be erased and not stored in a session like i want it to once the user is not on a page with $tid set in the url.
If you get $_GET['tid'] in url then set session again by that new value otherwise restore it from session. Thats it.
session_start();
$tid = (isset($_GET['tid']) && $_GET['tid']!="") ? clean_get($_GET['tid']) : $_SESSION['tid'];
Try this and tell me is it solved?
Use a function like isset() to see if it is being sent. Only then should you replace it:
if(isset($_GET['tid']))
{
$tid = clean_get($_GET['tid'])
// Do stuff to change session data.
}
I think what you are looking for is something like
session_start();
foreach ($_GET as $key=>$value) {
$_SESSION['getValues'][$key] = clean_get($value);
}
This will store all the values in $_GET in the $_SESSION. To retrieve the values later, you just have to use $_SESSION['getValues']['tid'] after calling session_start().
Here I'm assuming that clean_get() is just something that formats and/or escapes data that came in from forms, so calling it on each value before sticking into the session will do all that cleaning when needed.
Note: only call session_start() once, and make sure you do so before doing anything with $_SESSION, otherwise you'll get error messages.

Does "header()" php function unset global variables?

I am developing a php script which contains an html form.
If not all fields are filled in the correct way the script will signal an error and redirect back to the same page with the header function setting an error variable to yes with the get method:
header("Location: registration_page.php?error_empty=yes");
my script has an error handling part in which it highlights the fields containing a mistake, but I would like to keep the value of the fields correctly filled.
I am implementing this feature as I found in this other question:
How can I keep a value in a text input after a submit occurs?
but the problem is that when the page reopens the forms will not contain the old values.
My question is: does anybody know if the header function unsets global variables in the $_REQUEST array?
And do you know what kind of solution could I adopt?Maybe sessions?
Thanks in advance,
Matteo!
$_COOKIES will stay set, but $_POST & $_GET will be destroyed, as the client is moving to a new page. If they need to be retained, they must first be stored into $_SESSION before calling the redirect.
session_start();
$_SESSION['last_post'] = $_POST;
header("Location: http://example.com");
exit();
// On the redirected page, use the stored POST values and unset them in $_SESSION
session_start();
if (empty($_POST) && isset($_SESSION['last_post'])) {
$post = $_SESSION['last_post'];
unset($_SESSION['last_post']);
}
else $post = $_POST;
Does anybody know if the header function unsets global variables in the $_REQUEST array?
No, it doesn't. Cookies ($_COOKIE) will remain.
Obviously $_GET will contain whatever you have in the redirect (eg: $_GET['error_empty'] = 'yes') and$_POST` will be empty because you aren't posting.
So it $_REQUEST will be a combination of $_COOKIE and the new $_GET parameters you set.
You probably shouldn't be using $_REQUEST anyway. Specify exactly where you expect your request parameters to be...
It doesn't, but it does make a new request. A new request means a new $_REQUEST which does not necessarily have all of the old data. $_COOKIE will still be there but $_GET and $_POST will be new meaning that $_REQUEST will reflect that. ($_FILES will also be empty and while it is not in `$_REQUEST, it is another user-supplied value will be reset).
If you want to restore the form, you'll need to either put all of the variables in the url in the header, or use $_SESSION or setcookie and then restore from $_GET, $_SESSION or $_COOKIES.

Form validation losing variables

Let's say I enter a registration form with this ending URL: registration.php?accountType=a
The form is parsed on the same page (registration.php). If the user doesn't pass form validation they are taken to registration.php with error messages. So you see I lost my variable accountType=a. My question:
Can I submit a form for validation and retain the accountType variable? I'm aware that this could easily be done using a cookie. I just want a further understanding.
Solution: Although all of the answers below were valid, I went with a Session variable and <form action="registration.php?<?php print 'accountType=' . $_SESSION['accountType']; ?>" etc. Thanks for the help.
You should use this in your form:
<form action="registration.php?accountType=a">
You should use this in your php:
if ($validation_success) {
header('sucess.php')
} else {
// don't do anything. The page(registration.php?accountType=a) loads
}
I'm just giving you the idea.
You can easily to it in 3 ways...
Using PHP Sessions. Simply do something like
session_start();
$_SESSION['namespace'] = array('post' => $_POST, 'get' => $_GET);
Using Cookie (Session seems for me to be more elegant).
Use Ajax request; it will make your tasks easier.
I think you should add the "accountType=$accountType" at the url's end, when you make a http forward, so the user will taken back to the correct page.
I dont see your code, but maybe like this:
if(auth())
{
//do something...
}
else
{
header("Location: /registration.php?somerror=true&accountType=" . $accountType);
}

Problem with my implementation of the Post/Redirect/Get pattern

I always use the Post/Redirect/Get method on my forms. My forms generally always submit to themselves. However, when I have an error in the form, I don't send any new headers. This is so I can easily do stuff like this
<input type="text" name="email" value="<?php echo $this->input->post('email', '') ?>" />
The PHP is just a library function that handles 2 arguments, the $_POST key and a default value if it isn't present.
This means if someone makes an error in the form, they don't have to refill out the form a second time. The disadvantage is that reloading the page gives them the POST warning in their browser.
Is there anyway to avoid this, without using something for state (i.e. cookies, session, database etc)
I find the best way to do this is use the header function. You can post to what ever file you need even itself do the validation then use the header redirect to go back to the form if it failed. Store the post'd values in the session or another accessible variable, therefore you can access the previously entered data.
When using header("location: myscript.php"); make sure to include an exit(); afterwards otherwise you will still get the POST warning on a refresh.
myscript.php
if($_POST['submit'])
{
//check for errrors
if ($error)
{
$_SESSION['myPostVars'] = $_POST;
header("location: myscript.php");
exit();
}
}
<form>
// your form code
</form>
Edit: I just noticed that you edited your question to avoid using sessions.
You could serialize the post vars you want to return and put them in the query string (sent via the header()
There is no way to avoid this without saving state in the session. When you encounter an error you could probably do something like the following:
generate a unique id
copy the $_POST variable into the session keyed by the unique id above
redirect as you do now, but pass the unique id as part of the query string
update your library to look for this unique id in the session (error situations) instead of accessing the $_POST variable directly, if the unique id wasn't passed on the request or the name you are looking for doesn't exist use the default value
at the end of the request remove the unique id entry from the session. this saves polluting the session with too much garbage. You could also do this at the beginning of the request depending on your library
I think you mean something like this:
function Value($array, $key, $default = false)
{
if (is_array($array) === true)
{
settype($key, 'array');
foreach ($key as $value)
{
if (array_key_exists($value, $array) === false)
{
return $default;
}
$array = $array[$value];
}
return htmlspecialchars($array);
}
return $default;
}
<input type="text" name="email" value="<?= Value($_POST, 'email', ''); ?>" />
You may also want to read this tutorial.
You're basically doing it right. There's no particularly good way avoid the "repost" warnings.

Categories