Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting $_POST variables

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.

like image 246
Cody Thompson Avatar asked Apr 21 '26 23:04

Cody Thompson


2 Answers

You should either put that variable as an hidden field in your form, or use a session variable.

Hidden field

<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.

Session variable

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'];
?>

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

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.

like image 173
Jerska Avatar answered Apr 23 '26 15:04

Jerska


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';
like image 30
MrBoolean Avatar answered Apr 23 '26 14:04

MrBoolean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!