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 should either put that variable as an hidden field in your form, or use a session variable.
<form method="POST" action="someactionpage.php">
<input type="hidden" name="my_var" value="<?php echo $myvar; ?>" />
<!-- ... -->
</form>
And get it after in someactionpage.php with $_POST['my_var'] when the form is submitted.
Just store it whithin the $_SESSION variable
<?php
session_start (); // Just once at the beginning of your code
// ...
$_SESSION['my_var'] = $myvar;
?>
and retrieve it on another page with
<?php
session_start (); // Same than before
// ...
echo $_SESSION['my_var'];
?>
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
if (isset ($_SESSION['my_var']))
// Do stuff with $_SESSION['my_var']
or
if (isset ($_POST['my_var']))
// Do stuff with $_POST['my_var']
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.
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: https://www.php.net/manual/en/book.session.php
<?php
session_start();
$_SESSION['variable'] = 'my content';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With