Steeven
Steeven

Reputation: 4200

Why does this `$_SESSION = $_POST` fail?

What am I missing here? This is my PHP file:

<?
session_start();

echo print_r($_SESSION);
echo "<br>";
echo print_r($_POST);

// Save input in session
$_SESSION = $_POST;
echo "test1";
?>

<br>
test2

This file is accessed from a form submit, and I'm sure the post data exists. The output is:

Array ( [login] => 1 ) 1
Array ( [name] => test [type] => test ) 1
test2

and it makes no sense to me. The session content and post content are printed without problems.

But the $_SESSION = $_POST; appears to fail, and the rest of the script until the ?> doesn't give any response, which is obvious because the test1 text isn't printed.

I can't find out what happens with the $_SESSION = $_POST;. All questions I find on SO and elsewhere gives this way to store post data in the session.

I'm aware that session_start(); is needed prior to any output. Is there something else that is also needed in this case?

What am I missing?


Update - Test file

The exact code of a full test file (link removed) is:

<?
session_start();
?>

<html>
<head>

</head>
<body>

<?

echo print_r($_SESSION);
echo "<br>";
echo print_r($_POST);

// Save input in session
$_SESSION = $_POST;
echo "test1";
?>

<p>test2</p>

<form method="post" action="test.php">
    Type something to test: <input type="text" name="testfield" id="testfield">
    <input type="submit" value="Submit">
</form>

</body>
</html>

Update - Solved?

Okay, it is solved now. But this is STRANGE...

The problem appearently is caused by the comment. The // stops the script from running within the <?..?> brackets. When I remove the comment // Save input in session, then it works...?

Now WHAT am I missing here? It must be some php setting or something. Or maybe some file or script data that was changed. I guess that since @CodeCaster had it working, something happens on my PC that does it... But comments work anywhere else? Has anyone seen this before?

Upvotes: 0

Views: 2202

Answers (3)

Xesued
Xesued

Reputation: 4167

Working with Xampp, that example works just fine. The 'test1' is printed on the before and after a successful post. Using PHP 5.3.8.

Tested on Linux with PHP 5.3.6, also works fine printing the 'test1' in both cases.

So, it seems PHP is not the problem here.

Upvotes: 1

pcarvalho
pcarvalho

Reputation: 290

i would instead foreach the $_POST and add it to $_SESSION['mypostvars']. Keep in mind that you should validate and verify the $_POST before storing them.

this is a possible duplicated of PHP merge $_POST into $_SESSION

Upvotes: 2

user1130159
user1130159

Reputation:

Have you tried using $_SESSION['name'] = $_POST['name']; instead?

I've never used $_SESSION = $_POST;, and neither never seen it, in the whole time I programmed on PHP.

Hope this helps.

Upvotes: 5

Related Questions