设置$ _POST变量 [英] Setting $_POST variables
问题描述
我有一个使用POST的表格和一个变量. 我该如何在$ _POST中设置该变量,以便在提交表单后仍然可以获取该变量?
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?
我只是尝试
$_POST['variable'] = $variable;
它最终是空的.
推荐答案
您应该将该变量作为表单中的隐藏字段放置,或使用会话变量.
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>
提交表单后,使用$_POST['my_var']
在 someactionpage.php 中获取它.
And get it after in someactionpage.php with $_POST['my_var']
when the form is submitted.
只需将其存储在$ _SESSION变量中
Just store it whithin the $_SESSION variable
<?php
session_start (); // Just once at the beginning of your code
// ...
$_SESSION['my_var'] = $myvar;
?>
并使用
<?php
session_start (); // Same than before
// ...
echo $_SESSION['my_var'];
?>
其他信息
正如在某些答案和评论中指出的那样,您应始终检查是否存在该变量,因为您不能保证有此值.只需使用 isset函数
if (isset ($_SESSION['my_var']))
// Do stuff with $_SESSION['my_var']
或
if (isset ($_POST['my_var']))
// Do stuff with $_POST['my_var']
Kolink 在评论中指出,可以很容易地看到和更改字段值(通过POST发送)由用户.因此,除非确实不是关键信息,否则始终希望使用会话变量.
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.
这篇关于设置$ _POST变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!