I have a form using POST, and a variable. How would I set that variable in $_POST so that after the form is submitted, I can still get the variable?
I tried just
$_POST['variable'] = $variable;
It ends up empty.
I have a form using POST, and a variable. How would I set that variable in $_POST so that after the form is submitted, I can still get the variable?
I tried just
$_POST['variable'] = $variable;
It ends up empty.
You can use $_POST['variable'] = $foo to set a post variable. The $_POST['variable'] will continue to be set until the php script has finished executing, or until you use: unset($_POST['variable']). If you are trying to keep the variable around between sessions (which it sounds like), you should use a session.
in session 1:
to retrieve in another call to the server:
You can set $_POST['my_var'] (any name) either before or after submission:
(Note, field type does not have to be 'hidden' as posted earlier) If, say, you have code that processes the form from two different types of screens and must change one of the form vars after submission, merely do this in the post-submission code:
$_POST variables are sent from the previous page to the page you are currently in.
That means you shouldn't actually set a POST variable, you should only retrieve its content.
If you want to set a post variable for the next time you submit a form, you can do this:
This means the page you are submitting to will be able to access your variable this way:
If you want a variable to stay with a certain user, you should look into sessions.
PHP is a server side language! You cannot set a variable and use it on another instance. That means, that PHP resets all the stuff after you process an reload. To setup a variable which is defined after a reload you have to use the current session. See: http://de1.php.net/manual/en/book.session.php
Try this:
You should either put that variable as an hidden field in your form, or use a session variable.
Hidden field
And get it after in someactionpage.php with
$_POST['my_var']
when the form is submitted.Session variable
Just store it whithin the $_SESSION variable
and retrieve it on another page with
Additional info
As pointed out in some answers and comments, you should always check that the variable is present, because you have no guarantee of that. Just use the isset function
or
As pointed out by Kolink in the comments, a field value (sended via POST) can be easily seen and changed by the user. So always prefer session variables unless it is really non-critical info.