herondale
herondale

Reputation: 789

Session array resets on submit?

I have test.php:

<html>
<?php
if (!isset($_SESSION))
{
    echo 'session is not yet set';
    session_start();
    $_SESSION['comments'] = array();
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
<input type="text" name="comment">
Click the button!
<input type="submit"/>
</form>
<?php

array_push($_SESSION['comments'], $_GET['comment']);
echo 'Current array count: ' . count($_SESSION['comments']) . '<br>';

foreach($_SESSION['comments'] as $comm)
{
    echo $comm.'<br>';
}

?>
</html>

What should happen is that any text entered in the textbox should be pushed to the session array, but every time I click on submit, what is printed is the text I just entered instead of appending/storing the previous entries. I only get 1 as the array count all the time.

Every time I hit submit, session is not yet set always shows at the top of the page even when I have the if condition.

I can't seem to find what's wrong?

Upvotes: 1

Views: 717

Answers (3)

PHP Geek
PHP Geek

Reputation: 4033

You should start the session at the top of the page always.

session_start(); //start the session

Then we can check session is exist or not.

if(!isset($_SESSION['user'])){
     // your code
    }else{
     // your code
    }

Upvotes: 1

Difster
Difster

Reputation: 3270

You need to do this:

<?php
 session_start();
if (!isset($_SESSION))
{
?>

Otherwise you have header output from the HTML tag and the session can't start properly.

Upvotes: 1

Luke
Luke

Reputation: 640

session_start() does not just start a NEW session. If the client already has a session it resumes that session. PHP Manual
If you are using sessions, just have session_start(); at the top of the page and PHP will do the lifting of starting or resuming a session.

Upvotes: 0

Related Questions