Jurgen
Jurgen

Reputation: 274

$_SESSION message gets unset after header() is sent

SOLVED | UPDATE: As it was not that easy to find a solution, I post the answer below. Hopefully this will help others to find the solution easier on the stackoverflow.

I've got my own functions to set and show messages. Those messages are stored in session. What I want to achieve is to show a message just once after a form is submitted. And it works unless I use header() function to reload the page or redirect to another page.

I use ob_start() and session_start() on the top of my header. So these two are there all the time.

My message is set up by the function below. It creates a message of success or danger type and store it in a session variable.

protected function setMsg($text, $type) {
        if($type == 1) {
            $_SESSION["message"] = '<div class="alert green"><p>'.$text.'</p></div>';
        } elseif($type == 0) {
            $_SESSION["message"] = '<div class="alert red"><p>'.$text.'</p></div>';
        }
    }

The other function shows message just once and after that it is unset.

public function showMsg() {
        if(isset($_SESSION["message"]) && !empty($_SESSION["message"])) {
            echo $_SESSION["message"];
            unset($_SESSION["message"]);
        }
    }

And here is the final piece of my form submission code:

$this->setMsg("User has been created", 1);
header("Location: users_list.php");

If I don't use the header() function, then it's alright. But I must use it.

The message function is called out in the header, but below all the other functions:

<?php $data->showMsg(); ?>

So, it seems that page gets redirected twice somehow. After the first time the message gets unset, and after the second refresh I just can't see it. So I can't see it at all.

What more likely I'm doing wrong?

Upvotes: 1

Views: 385

Answers (1)

Jurgen
Jurgen

Reputation: 274

Finally I figured it out. In this particular case I just need to insert exit() right after calling header() function. And that's it.

Upvotes: 1

Related Questions