PHP + Logout Member when Session Expires - php

I've a site where people login and a SESSION is created.
I have noticed that if you leave the site for long enough (not sure exact time frame) the session ends but the members is still in the site. They can still click and navigate around and I believe this has resulted in some meaningless data in the DB as SESSION variables like userID don't exist.
I was looking for advice around logging users out when the SESSION ends.
I have looked at code like this - any better ideas?
<?php if(!isset($_SESSION[]) {header(loginpage.php);}?>
Is there a better way to write the above code?
Where should this code be placed? Just on the navigation menu or really on any place a user can click?
Finally is there a way to understand when the SESSION naturally expires - is there a SESSION variable I can print to screen to see the timeleft etc?
thanks

You need to validate the session, you already headed into that direction with your code, but it's not enough:
<?php if(!isset($_SESSION[]) {header(loginpage.php);}?>
It's not enough because $_SESSION[] exists automatically after the session is started (the session mechanism in PHP, see session_start).
Instead, if you have saved the userID inside the session, check that one:
isset($_SESSION['userID'])
If the session really expired, it should not be set.

I agree with the above answer. I would say it depends on how your application is architected to say where this belongs. before there is any output to the screen I am assuming your calling session_start, then immediately check for a session variable such as userID that gets set after a user logs in. if it's not set redirect setting a header for location to your login page. you could also write some js that checks the session cookie for a value at a specified interval(I believe, it's been a while so test it out), then when the variable isn't present you can redirect to the login page. a third way would be for the js code to make an XHR call to a php script to check out the session for you.

Related

php PHPSESSID exists but session destroyed

I am trying to login an user for 2 weeks if user login with remember me check then i have set some variables in session and cookie set for 2 weeks. It is set correctly i have printed it and got the value session_cookie_lifetime = 1209600 and session_gc_maxlifetime = 1209600. I also print session and got correct value in $_SESSION.
After login in my site when i shut down my computer and reopen my site it seems that it is working (it is keeping me as login user). But when i shut down my computer and next day when i open my browser it is not working and it is showing that i am not login on my site. I have printed $_COOKIE and $_session . It shows that in cookie there is :
[PHPSESSID] => svikos35bgclmebk2cqraiddt2
But session is empty.
I got this form modx stuff:
MODx automatically starts and ends sessions with each request made to the site. You can simply save values into the $_SESSION array and they will be saved in between requests so you can use them on subsequent pages (so long as you have the same user session). Not really any magic to it other than don’t call the session functions yourself to start, end, or otherwise manipulate the session configuration—that can all be done via settings in MODx.
I am using modx revo. It is a bit descriptive question. let me know you need something else.
Anything that may help me (blog link,any settings, any suggestion ) will be highly appreciated.
Thanks in advance
This only happens after a day?
Could tmpwatch be deleting session files from the server?
session_cookie_lifetime and session_gc_maxlifetime doesn't garantee you, that session will be saved for a week. GC kill unused sessions. Check PHP documentation about this parameters and you see, that you can't be sure, that your session will be on the server and you don't be sure, that your sesssion will be destroed after this time. GC is async.
You need to recreate $_SESSION after login (and autologin) if it doesn't exists.
Check this article (in russian, try google translate:
PHP GC: unexpected behavior
The basic idea behind SESSION is that, When you create or call session_start() method your server generate a session id and store it on server memory. Also the server create a cookie on your client machine that cookie contains an id that is related to your server side session id. When you call session_destroy() method server delete that id on server side but the client side cookie doesn't. That is why your session id still shown. You can also check by cache and cookie clearing. When you clear cookie your session will destroyed.

EMPTY SESSION MANY TIMES PHP

I make this post because I am really confused about session in PHP. I have a page (index.php) and I save in session a lot of variables (for example, one of this is $_SESSION["FID"]) and i redirect the user in a third party iframe. When the user enter successful his data in iframe, the iframe redirects the user again in index.php and also saves in session other variables.
When the user enters again in index.php I check the session, which comes from iframe (every time the session is set) and after that I make a check if $_SESSION["FID"] isset.
The problem is that most of the times (regardless the browser or something else), $_SESSION["FID"] is empty. Why is this happening? How can I find a solution in this?
I 've tried to be clear and not to confuse you.
You must put session_start(); at the top of every page you want you $_SESSION data to exist.

PHP: Session variables

I am beginning to learn php. I have a question regarding sessions.
Right now, I know that session_start() creates a session variable.
What I don't know is, when I access the session I created, do I need to use session_start() again?
If yes...
Why is this? Because I already created a session and I wonder why it wouldn't last the entire browsing session.
because what i understand from it is, that it is going to create a new session.
No:
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
http://php.net/session_start
Each new page you visit is an entirely new context for PHP. session_start allows you to reestablish a previous context/session/data.
The session_start function tells PHP to enable session tracking. It doesn't wipe out the session created by a previous page. You must call session_start() before you'll have access to any variables in $_SESSION.
Because of the manual session_start()
session_start — Start new or resume existing session
the same way you would connect to database every time you want to use it. it will connect to however you're storing your sessions. The session variables are no wiped out.
Also read more here but this should help to understand how sessions work:
When you are working with an application, you open it, do some changes
and then you close it. This is much like a Session. The computer knows
who you are. It knows when you start the application and when you end.
But on the internet there is one problem: the web server does not know
who you are and what you do because the HTTP address doesn't maintain
state.
A PHP session solves this problem by allowing you to store user
information on the server for later use (i.e. username, shopping
items, etc). However, session information is temporary and will be
deleted after the user has left the website. If you need a permanent
storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store
variables based on this UID. The UID is either stored in a cookie or
is propagated in the URL.
Session data is stored at the Server side but the reference or id to the session is stored on the client's browser cookie. For the server to know your session id we make a call to session_start() on each page it is required (at the top) so that the first thing done is to get the id from the user and retrieve the session data. It is required on every page whenever you want to access session data.
Here is a video tutorial also. http://blip.tv/step4wd/php-sessions_en-5983086
The answer is yes. You have to do that on every page. If you don't do that you get a undefined index error.
This will work because we include the file
Index.php
<?php
session_start();
//file doesn't have session_start
include "file.php";
?>
No: it is NOT always going to create a new session. It only tells the script that this page wants to start OR maintain an existing session.
A session is nothing more that a STATE AT THE SERVER that you carry from from page to page.
It is NOT accessible from the client (browser).
The only thing the browser must do to keep the session is passing an ID (called default PHPSESSID in PHP).
This ID can be stored in a cookie, GET or POST, as long as you get it transfered to the server with each request you make.
Youve to use session_start(), everywhere you need to work with session like, creating, accessing, destroying.
Unlike cookies, you can't access or work with session unless you initiate the session.

PHP: User logged in sessions and cookies

Sorry for the newbie question! I'm making a small website that allows users to create their own accounts. It's not a banking system, and it's unlikely that someone would want to hack it. That said, I am trying to make it reasonably secure, as there are plenty of bored script kiddies out there.
Could someone describe a basic workflow for a user logging in and having a cookie set that will keep them logged in for 30 days?
At the moment I have the following:
Validate and sanitize inputted data.
Check supplied credentials against bcrypt hashed password in DB.
If correct then call "Login" function.
Login function:
a. Delete any session data from DB with userID (table with two columns: SessionString and UserID).
b. Add new session data to DB (newy random generated string and UserID).
c. Write random generated string and UserID to cookie.
d. Set $_SESSION("UserID") with $userID.
But although the two cookies are being created and written to, the $_SESSION("UserID") remains blank... I'm guessing because I can't write to $_SESSION any time I like?
And even once that's fixed, how do I use the data stored in the cookie to log a user in? I'm guessing I don't want to go to the DB on every page load. And it will still require me to create a database object to see if the credentials in the cookie are ok. Is this the right way to this?
Once again, apologies for the newbie question!
UPDATE:
Yes, I do understand the difference between $_SESSION variables and a cookies. I also have session_start() at the top of every page (right after <php with no blank lines). $_SESSION("UserID") just remains blank.
Here's the code from the top of the page:
<?php
session_start();
if(!isset($_SESSION['initiated'])) {
session_regenerate_id();
$_SESSION['initiated'] = true;
}
Thanks for the help.
First off, there is an important difference between a session and a cookie. When you use the $_SESSION[".."] you are creating a session (which lives on the server, compared to a cookie which lives on the client), even though the browser uses a cookie to keep track of the session id. To create a cookie you would use the setcookie() method.
That said, I would recommend you to read through this article which is a step-by-step guide on how to create a secure login script, with persistence using a cookie for a "Remember me"-feature. Describe how to do it in detail would be to extensive for an SO answer im afraid.
Side note:
To be able to write to the session, you might have to call session_start(); prior to getting or setting a session variable using $_SESSION[".."].
Did you write a custom session handler that has your session-files stored in the db? I guess you don't.
If you want to use $_SESSION you have to also do session_start(). When using PHP sessions the cookie to identify the user will be set for you. You will also get session files created in your /tmp directory. That's the location your variables and anything you assign to $_SESSION will be stored.
Unless you define a custom session handler, that will manage the location of the session files, you won't need to query your database. Just save the users credentials in $_SESSION.
See this Tutorial on how to use PHP sessions.
PS: You access arrays like this: $_SESSION["UserID"], not with ().
you might want want to look at this article in which i have already discussed about various types of session hijacking and how you could avoid it.
session security in php

problem with sessions and redirection php

Im setting a session variable on hypothetical page number 1. The user then clicks a link to go to a site off the server, and then comes back to page number 1. Problem is, the session variables i set on page one, are no longer set when the user comes back.
Is this a known issue with php, is there any work around?
I am starting the session on the page, and i am echoing the session variables after i set them to make sure they set and they are.
Not sure where to go with this.
Are you sure you call session_start() in all the scripts that use the session variables?
it is possible that the session timeout has expired when the user comes back .. also i think the session has a feature to check for referrers , so u can check that too .. also make sure when the user comes back he lands on the exact same domain
You need to store the session ID in a cookie, and then read that cookie when the user comes back.

Categories