Session_start does not maintain variables on homepage only - php

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 :)

Related

Prevent user to access if has not logged in

I am currently working on developing a simple web system, so an user first will be directed to a login page, then a processing page. If its account data provided is correct, it will be directed to the main page, so it can carry out some actions, at last it can logout.
So what I want to ask is: how can I prevent user to access the processing, main or logout page before they login, I mean, if I do not limit it, the login action is by some means useless. I am using wamp to develop the web system.
I have considered making use of the session variable, however, I have no idea how to check the value of the variable. If I start a session at the login page, so if I skip the login page but directed go to the main page, do I have those session variable present in the main page?
1) Add session_start(); at the top of the php page to initialize sessions.
2) Add if statement
if($_SESSION['logged_in'] == 1) { ..show page.. } else { show login page }
3) Create a login form which validates data, if data is correct then it adds $_SESSION['logged_in'] = 1; and redirects to profile page with logout button.
That's all :)!
I suggest that you check some tutorials, since it will give you some more information how to do that - http://www.intechgrity.com/create-login-admin-logout-page-in-php-w/ or any other link via google - "How to create login/logout functions with SESSIONS".
About your question, in each page you will put session_start(); at the start of the file, they will have all sessions you have specified for user.
EDIT:
Added few useful links -
http://www.php.net/manual/en/book.session.php
http://www.tizag.com/phpT/phpsessions.php/
http://www.w3schools.com/php/php_sessions.asp
well,this is what i will do. Check with an if statement if a session variable that holds, for example, the username from the login page exists, then if it doesn't show an error 404 page, or redirect the user to any error page...you might want to create that yourself anyway (so that it redirects them back to the login page).
<?
session_start();
if(!$_SESSION['username']){
header("Location: HTTP/1.1 404 File Not Found", 404);
exit;}
?>
You could also create a new file and place this code there so that you call it on everypage that will require a user to login before accessing it....
but try to access non login page for the first time then you will be redirected to login page then try to access the same non login page for the second time you'll have the access already even you didn't log-in.

Prevent back button after logout

I don't want the user to go back to secured pages by clicking back button after logging out. In my logout code, I am unsetting the sessions and redirecting to login page.But, I think the browser is caching the page so it becomes visible despite the session being destroyed from logout.
I am able to avoid this by not allowing the browser to cache
header("Cache-Control", "no-cache, no-store, must-revalidate")
But this way I am loosing the advantage of Browser Caching.
Please suggest a better way of achieving this. I feel, there must be a way of handling this by javascript client side
Implement this in PHP and not javascript.
At the top of each page, check to see if the user is logged in. If not, they should be redirected to a login page:
<?php
if(!isset($_SESSION['logged_in'])) :
header("Location: login.php");
?>
As you mentioned, on logout, simply unset the logged_in session variable, and destroy the session:
<?php
unset($_SESSION['logged_in']);
session_destroy();
?>
If the user clicks back now, no logged_in session variable will be available, and the page will not load.
I was facing this same problem and spent whole day in figuring out it,
Finally rectified it as follows:
In login validation script if user is authenticated set one session value for instance as follows:
$_SESSION['status']="Active";
And then in User Profile script put following code snippet:
<?php
session_start();
if($_SESSION['status']!="Active")
{
header("location:login.php");
}
?>
What above code does is, only and only if $_SESSION['status'] is set to "Active" then only it will go to user profile , and this session key will be set to "Active" only if user is authenticated... [Mind the negation [' ! '] in above code snippet]
Probably logout code should be as follows:
{
session_start();
session_destroy();
$_SESSION = array();
header("location:login.php");
}
Hope this helps...!!!
Here's an easy solution which I have used in my application.
Add the below code inside script tag in the login HTML page (or whichever page it redirects to after logout)
<script>
history.pushState(null, null, null);
window.addEventListener('popstate', function () {
history.pushState(null, null, null);
});
</script>
It will disable the back button. You will not be able to go back by clicking on the back button.
Note: Not tested on Safari.
I think your only server side option is to disallow caching. This is actually not that bad if you are using a Javascript heavy application as your main HTML might only be a series of JS calls and the Views are then generated on the fly. That way the bulk of the data (JS MVC and core code) is cached but the actual page request isn't.
To add to the comments pasted below I would suggest adding a small AJAX call during load time that fires even for cached pages that goes to your backend and checks the session. If not session is not found it would redirect the user away. This is clientside code and not a secure fix, sure, but looks nicer.
You could get this off your conscience with
A cheap fix if all else fails would be a "Please close this window for security reasons" message on the logged out page. – izb May 9 '12 at 8:36
But like N.B. said
You don't have to disable anything. If they go back, they're served the cached version of the restricted page. If they try to click around it, nothing will work because the appropriate session won't be set. – N.B. May 9 '12 at 7:50
You could insert a condition/function on each restricted page, checking if the appropriate session variable is set or not. This way, you can print 2 versions of the page (one for the valid users, and one redirecting to the login page)
Avoiding the user to go back is not a good reason and most of all not secure at all.
If you test the user's session before every "admin" action made on the website, you should be fine, even if the user hit the back button, sees the cached page and tries something.
The "ties something" will return an error since the session is no longer valid.
Instead, you should focus on having a really secured back office.
Here's an easy and quick solution.
To the login form tag add target="_blank" which displays content in a different window. Then after logout simply close that window and the back button problem (Safari browser) is solved.
Even trying to use the history will not display the page and instead redirect to login page. This is fine for Safari browsers but for others such as Firefox the session_destroy(); takes care of it.
the pages on which you required loged in, use setInterval for every 1000 ms and check wheather user is logged in or not using ajax. if user session is invalid, redirect him to log in page.
Note that although users can't change anything after resetting session data and/or cookie, they still may see usual information accessible to a logged in user as they appeared on the last visit. That is caused by browser caching the page.
You have to be sure to add the header on every page accessible by a logged in user, telling the browser that the data is sensitive and they should not cache the script result for the back button. It is important to add
header("Cache-Control: no-cache, must-revalidate");
Note that those other elements other than the immediate result of the script under this header, will still be cached and you can benefit from it. See that you gradually load parts of your page and tag sensitive data and the main HTML with this header.
As the answer suggests, unsetting the logged_in portion of $_SESSION global variable can achieve logging out, but be aware that first, you don't need to destroy session as mentioned in the PHP's session_destroy() documentation
Note: You do not have to call session_destroy() from usual code. Cleanup $_SESSION array rather than destroying session data.
And second, you better not to destroy the session at all as the next warning on the documentation explains.
Also, unset() is a lazy function; meaning that it won't apply the effect, until next use of the (part of the) variable in question. It is good practice to use assignment for immediate effect in sensitive cases, mostly global variables that may be used in concurrent requests. I suggest you use this instead:
$_SESSION['logged_in'] = null;
and let the garbage collector collects it, at the same time it is not valid as a logged in user.
Finally, to complete the solution, Here are some functions:
<?php
/*
* Check the authenticity of the user
*/
function check_auth()
{
if (empty($_SESSION['logged_in']))
{
header('Location: login.php');
// Immediately exit and send response to the client and do not go furthur in whatever script it is part of.
exit();
}
}
/*
* Logging the user out
*/
function logout()
{
$_SESSION['logged_in'] = null;
// empty($null_variable) is true but isset($null_variable) is also true so using unset too as a safeguard for further codes
unset($_SESSION['logged_in']);
// Note that the script continues running since it may be a part of an ajax request and the rest handled in the client side.
}

When to start a session?

I have a system that requires the user to login (or register) for an account before they are able to access their Member 'dashboard'.
My question is... at what point so I session_start()? On the login page and the register page? or after the user has successfully authenticated?
Thanks.
You need to include session_start() on every page where you want the session data to be accessible. And it needs to be called before any other output has been done.
As Helge Helwig said,
you need to add session_start() in the top of every page.
However, to make this easier, you can create a PHP document, where
you store all vital code like this, and call it; say init.php.
Then you can include 'init.php' at the top of every page, which would
clean up the code a bit.
Start a session on the page(s) that need to access session data. As part of a successful login, you should also call session_regenerate_id to prevent session fixation.
you can start session once user is authenticated.
after that you can user related information in S_SESSION and access this info from anywhere.
You should start session after verifying user's information, and than you can set user's uid to session variable. which could be useful afterwards in loading user's personal information like profile,preferences etc.
on register page i think you do not need to start session.
Regards
Your session_start() will be called on each and every page that is secure and that is accessed after authentication. You will put the values in session both in login and register pages as they authenticate user. But once the user is verified, now you have to put this function on all pages which needs authentication of the user.

Redirect to page user was trying to get to after logging in

Been reading a bit to find the answer with not too much luck.
I have a site where members can browse the site anonymously but some pages are restricted. I have the members redirected to a login page once they click a link that needs them to be logged in to view.
The problem I'm facing is I don't know how to redirect the member to the page they were trying to get to once logged in.
They tried to to get to /profile.phtml , it sent them to /login.phtml , now when they log in, I want them to be sent to /profile.phtml because that's where they clicked to get to. If they clicked /album.phtml, I want them to be sent to /album.phtml after login.
Can anyone help? Do I somehow store the URL in a session?
Much appreciated.
Just before making the header("Location:") call to redirect, store the page they're currently on in $_SESSION['redirect_to']. Upon successful login, make another header() call to redirect back to the original page and unset the session variable so it doesn't get accidentally reused anywhere.
$_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
header("Location: http://example.com/login.php");
exit();
// On successful login
$redirect = $_SESSION['redirect_to'];
// unset the session var
unset($_SESSION['redirect_to']);
header("Location: http://example.com/$redirect");
exit();
You could very well use a session variable like other people are suggesting. However, I'd rather rely on HTTP_REFFERER. The drawback here is not every browser sends a referrer, but most major browsers do. It's a part of the HTTP standard and I think it's good enough. Stick this in your login script.
if(!empty($_SERVER['HTTP_REFERER'])) { header('Location: '.$_SERVER['HTTP_REFERER']); }

PHP Logout Problem?

when a user logouts from my web site they are logged out but on the logout page there username and the log out link and profile link are still visible on the logout page but not on any other pages.
All I want to know is how do I change the logout page so that the log out and proflie links and username are not displayed like the rest of the pages.
I'm using the same file where the links and username are displayed for every web page so what is the problem with the logout page?
Please leave a code sample to solve this problem if possible?
If you’re using a session based authentication, make sure that you reset the $_SESSION variable as session_destroy does not do that. So:
session_destroy();
$_SESSION = array();
I can only guess that your logic goes something like:
Display page header including logo, logout button and links;
Process the logout request.
I'm assuming that (1) will do things like display the right links and the username (if logged in). The point is that you're doing checks on being logged in before you log the user out. If so, just change the order:
Logout the user;
Display the page header, etc.
But it's hard to say definitively because I'm guessing at your page structure.
it sounds like you include the code that displays the logout and profile links before you actually do the processing to log the user out. try seeing if you can rearrange the execution of your code so the include comes after youve already logged the user out.
<?php
session_start();
$_SESSION = array();
session_unset();
session_destroy();
header('login.php')
?>
Maybe you can try my method
You can try things as per other answers ..
Or just create a logout.php .. which doesn't output anything so you just start the session, destroy all of the session or the required keys and then redirect the user to a logout_done.php which outputs, something like, You have been successfully logged out blah blah ..

Categories