开发者

Saving post values in a session array

开发者 https://www.devze.com 2023-02-08 23:39 出处:网络
I want to save values send via POST in a session array: $reply = array(\'thread_id\', \'reply_content\');

I want to save values send via POST in a session array:

$reply = array('thread_id', 'reply_content');

$_POST['thread_id'] = 2; # test it

$_SESSION['reply'] = array();



foreach ($reply as $key)
{
    if (in_array($key, $_POST))
    {
        $_SESSION['reply'][$key] = $_POST[$key];
    }
}

var_dump($_SESSION['reply']);

For example I want to check if the keys 'thread_id' and 'thread_content' are send in post, if they are then I want to save them in a session array called reply, using the same keys.

So for example if 'thread_id' is send via POST:

开发者_如何学C$_POST['thread_id'] = 'blah';

Then this should get saved in a session called 'reply', using the same key:

$_SESSION['reply']['thread_id'] = 'blah';

How can this be done?


In general, your approach looks valid, but I'm going to guess that you may not be calling session_start(), which is necessary to persist session data.

session_start();

if(!$_SESSION['POST']) $_SESSION['POST'] = array();

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

var_dump($_SESSION['POST']);


in_array($needle, $haystack) checks whether $needle is a value in $haystack and not a key. Use array_key_exists or isset instead:

foreach ($reply as $key)
{
    if (array_key_exists($key, $_POST))
    {
        $_SESSION['reply'][$key] = $_POST[$key];
    }
}

Or:

$_SESSION['reply'] = array_merge($_SESSION['reply'], array_intersect_key($_POST, array_flip($reply)));


Use this

  $reply = array('thread_id', 'reply_content');

    $_POST['thread_id'] = 2; # test it

    $_SESSION['reply'] = array();
    foreach ($reply as $key)
    {
        if (isset($_POST[$key]))
        {
            $_SESSION['reply'][$key] = $_POST[$key];
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消