I have a website that needs to show a block of welcome text after you have logged in. What would be the be开发者_StackOverflow社区st way to accomplish this in php so that it only shows when logging in and not when you have already logged in and are visiting the page?
Here's a basic session example:
// on page where accepting the login POST
session_start(); // initialize session.
// store that logged_in is true. You might want to put a username here instead.
$_SESSION['logged_in'] = TRUE;
// store that they need to see the message still.
$_SESSION[ 'show_login' ] = TRUE;
Then later:
// on all other pages at the top (before whitespace even)
session_start(); // you still have to initialize the session.
// other pages where actually outputting welcome text
// is the user logged in?
if( isset( $_SESSION[ 'show_login' ] ) && $_SESSION[ 'show_login' ] )
{
// gotta clean up our flags.
$_SESSION[ 'show_login' ] = FALSE;
// Then HAPPY DAY! We can say hello.
echo "Hey! I know this guy.";
}
else
{
// we are actively hostile to those who are not logged in...
// you may want to be more cordial.
// sometimes it is so obvious that I come from NJ...
echo "I've never seen you before in my life. He smells";
}
Utilize $_SESSION
and save to there.
In your login script, add a flag to the user's session, say $_SESSION['justloggedin'] = true;
. Then, assuming you're including a common file on all your pages, simply check if that flag's present:
if ($_SESSION['justloggedin'] === true) {
... display welcome message
$_SESSION['justloggedin'] = false;
}
This way, they log in, they get redirected, and no matter which page they land on, the welcome message will be displayed. After that, each subsequent page will not show the message because you cleared the "show the message" flag as part of showing the message.
精彩评论