php 在 SESSION 中存储所有 POST 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14465464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:19:44  来源:igfitidea点击:

Storing all POST data in SESSION

phpsession

提问by TNK

I have more values (over 20) from $_POST like this...

我有更多的值(超过 20 个)来自 $_POST 像这样......

$name = $_POST['name'];
$username = $_POST['username'];
$city = $_POST['city'];
$mobile = $_POST['mobile'];
$address = $_POST['address'];

NOTE : I have prevented there values from SQL injection.

注意:我已经阻止了 SQL 注入的值。

My question is can I know is there a way to store all these POST values in SESSION at once? Instead of this method..

我的问题是我能知道有没有办法一次将所有这些 POST 值存储在 SESSION 中?而不是这个方法..

$_SESSION['name'] = $name;etc

$_SESSION['name'] = $name;等等

any answers will be highly appreciated. Thank you.

任何答案将不胜感激。谢谢你。

回答by Mattt

$_SESSION['post-data'] = $_POST;

That will create an array of the post values in a single session variable. The values would be accessible as

这将在单个会话变量中创建一个帖子值数组。这些值可以作为

$_SESSION['post-data']['name']
$_SESSION['post-data']['username']
...

回答by Mirko Adari

You can add one array to another.
$_POSTand $_SESSIONare just arrays.
Note that the keys in the second array take priority in case of duplicates.

您可以将一个数组添加到另一个数组。
$_POST并且$_SESSION只是数组。
请注意,在重复的情况下,第二个数组中的键优先。

$_SESSION += $_POST;

However, I don't see this ending well, since the client side can inject anything he wants to the session, E.G. hiHymaning your users session id.

但是,我不认为这个结局很好,因为客户端可以向会话注入他想要的任何东西,例如劫持您的用户会话 ID。

回答by PhearOfRayne

If you looking for session variables that are set using the same key as the posted array, you could use this:

如果您要查找使用与已发布数组相同的键设置的会话变量,则可以使用以下命令:

foreach ($_POST as $key => $value) {
    ${$key} = $value;
    $_SESSION[$key] = $value;
}

This will make your $_POST array into variables based on the array key and also set the session at the same time. You could then access your namepost by using either $_SESSION['name']or $name.

这将使您的 $_POST 数组基于数组键变成变量,并同时设置会话。然后,您可以name使用$_SESSION['name']或访问您的帖子$name

This means you will not need to use: $name = $_POST['name'];anymore. As the above code will set the name variable for you and also set the session variable.

这意味着您将不再需要使用:$name = $_POST['name'];。由于上面的代码将为您设置名称变量并设置会话变量。

回答by Jaro

The best explanation of passing variables either with form post or header location redirection inside php check out my answer in this thread: How to pass variables received in GET string through a php header redirect?

在 php 中使用表单发布或标头位置重定向传递变量的最佳解释请查看我在此线程中的答案:如何通过 php 标头重定向传递在 GET 字符串中接收的变量?