'how to show session variables only when appropriate?

I have a php1 page that transfers the user to a php2 page which sets the session variable and transfers the user back to the php1 page. e.g.(login form displaying an error message) Now when I wanted to display that session variable in php1 so I tried the following:

if(isset($_SESSION['messages'])){
  echo($_SESSION['messages']); 
}

the problem is that it will keep being displayed even if the user refreshes the page since the variable is still set. ps: I tried to use onload() and onunload() functions to unset it but it did not work, but I'm not sure if I did any mistakes.



Solution 1:[1]

Remove the session variable after you show it.

if(isset($_SESSION['messages'])){
    echo($_SESSION['messages']); 
    unset($_SESSION['messages']);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar