1

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:

$_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?

4
  • Does the code you wrote not work? You're asking how to do it but your question includes the code to do it. Commented Feb 5, 2011 at 17:59
  • Just use save it as $_SESSION['reply']['thread_id'] = $_POST['thread_id];. Commented Feb 5, 2011 at 17:59
  • the code seems correct. Is the session initialized correctly? Commented Feb 5, 2011 at 18:03
  • session_start is there...I forgot to add it here Commented Feb 5, 2011 at 18:13

3 Answers 3

2

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']);
Sign up to request clarification or add additional context in comments.

Comments

1

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)));

Comments

0

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];
        }
    }

1 Comment

in_array will check for the values not for keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.