Session_start does not maintain variables on homepage only
I use PHP sessions with session_start()
to maintain state of which user is logged into my site. This works fine by just calling session_start()
and the top of all my files once the user is logged in.
However, I'd like to have it so when they click the site's icon in the menu bar, if they are logged in it won't send them to the homepage but rather to their logged in personal page. However, a simple session_start()
to recognize the user is logged in and redirect them at the top of the homepage does not work.
开发者_如何学运维None of the session variables are recognized from the home page. Yet the session is not actually killed - I can go back in the history and am still logged into the site. Would there be a reason the homepage should give different behavior than every other page?
No, it shouldn't be different. In order to see what variables are available in your $_SESSION, you can do this
var_dump($_SESSION);
If it's empty then there is a problem. You can try to see the session_id with the method
echo session_id();
It should be the same session_id in both your logged page and home page. If this is not the case, maybe you are messing up with cookies?
Make sure that session_start()
is only being called once. If you call it twice, it could interfere with the session handling. I would recommend that you call session_start() on every page the user can be logged in on (frankly I see no reason not to call it on every page period, but someone please correct me if this is bad) but only once. At that point, you can check the _SESSION
and see if the user's logged in key is set. If so, redirect them.
if u are calling session_start()
on each page and you don't know that a session is already strated in your include/require pages then use @ like this @session_start()
note: although this is not good practice to use @
to send a user to their personal page rather than home page
..u need to develop a logic and also personal page will be based on user id of logged user.On home page something like below
home.php(raw code)
<?php if(!empty($_SESSION['user_id'])) {
header("Location : personal_page.php?id=".$_SESSION['user_id']);
exit();
} else {
//your page code
}
?>
for login via history pages problem:
you create a logout.php to end user session, do not forget to start the session in this page!, using session_start()
at the very begging of your script. Thus,
session_start();
session_unset();
session_destroy();
will be the right sequence to end a user's session.
reference
Happy To Help :)
精彩评论