Using PHP Sessions - php

So, I've been playin' around with sessions in PHP today, and after procrastinating over whether I should use sessions or not since I started PHP about 6 months ago (it looked scary), I've found it to be quite simple. But I am using time() as a session id, I'll explain why...
I found a page on session reference in php.net website, and one of the code samples uses this to manage sessions:
session_start();
if( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 60)
$_SESSION['last_access'] = time();
However, this expires very quickly. Ofcourse, I COULD change 60 to a very high number, but this is for a website where customers will be spending on average, 3 - 4 hours just adding products to the shopping cart, so I can't have sessions expire unless they close the page.
How can I transfer the same session id over to all pages on our site regardless of time(). I don't really want to be using time to manage session id's.
I DID use the constant SID in a url like this:
<?php echo 'go to another page'; ?> however, using the constant, as advised by the PHP website, does not work.
Can someone please help me maintain the same session id, regardless of time, across the whole site?
Your help is much appreciated, and thanks! :)

I think you may have a misunderstanding of sessions. Assuming, their cookies are enabled, you will never need to use a session ID. The session ID itself is stored in a cookie. If you would like to keep a session alive longer, simply use ini_set('session.gc_maxlifetime', 20); and change 20 to the amount of minutes you would like it alive for.
Please keep in mind you must use start_session(); at the very top of each file to make sure that specific file uses sessions. (This would be a good reason to have 1 main included config file at the top of the php files, so u can easily add that to the 1 file and it is added to all pages)

Related

how to timeout users from website?

Do you use cookies or session to time out or lock out someone from your website if they have used it for 2 hours? I want it to lock and have them wait an hour before them using it again.
I got the idea from this website that had a message pop up and say
"you have used this site for 2 hours, please wait an hour and come back or become a member and get unlimited hours"
Two approaches:
The simple one, in which you set a cookie or session (both use cookies in the end, so it hardly matters) to identify a user. The problem with this is that a user may simply discard his cookies or use a different browser, so this solution will only ever work for rather clueless users. It is probably good enough for your use case.
Go crazy with fuzzy identification of users via neural networks, which may/would allow you to identify users pretty uniquely in a way that would not allow them to "change their identity" easily. This is a really complex solution though and may be overkill or unrealistic for your purposes.
probably this will be helpful to you
if( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 60 )
$_SESSION['last_access'] = time();
This will update the session every 60s to ensure that the modification date is altered.
please visit below link to know more details with php code
http://riturajkumar12.blogspot.in/2014/04/expire-session-automatically-after.html

php keep session alive for multiple days

I have an app where I would like to enable users to choose to stay logged in for a fairly long period of time, say 3 days similar to google mail, facebook or linkedin. (It is meant to be accessed primarily by phone and data is far less sensitive than other stuff on phone.) Right now I am setting about four session variables on log in, such as id of user, name, etc. so to avoid a lot of recoding and lost functionality, I'd like all of these variables to remain accessible.
Is there a way to increase session length to 72 hours when setting the session variables?
Alternatively, if you need to set cookies, what is best practice to achieve long logged in time when there are a number of session variables set.
Thanks.
You can set session for various ways. One of the ways is to set it in php.ini
session.gc_maxlifetime = 360*72
with php you can do it with
ini_set(’session.gc_maxlifetime’, 360*72);
you can also use
session_set_cookie_params(360*72,"/");
http://pl1.php.net/session_set_cookie_params
it sets session cookie. You can also serialize $_SESSION and set it in cookie.
I guess it is possible only by writing session to database
you can set a long live cookie & check value of the same on user request after many days.
use cookie value as a key in table to validate user identity.
then reload session of that user from database.
Maybe you could use the session storage of local storage features of HTML 5 ?
I know it is not purely the same thing as cookies, but I just wanted to propose this. Maybe it could help :)
There might be a little version problem with older versions of browser on phones. You can check them with : http://caniuse.com/namevalue-storage
And there's another thing. You can use "Remember Me" cookies for long term storage of important informations. Extending the lifetime of cookie is, as far as I know, not a "good practice".
You can do this by sending a post every 5 minutes to a php function that stores the session id in a variable, then destroys the session, creates it again and gives the session id again:
<?php
function restart_session(){
$user_session = $_SESSION['id'];
session_destroy();
session_start();
$_SESSION['id'] = $user_session;
}
?>

Zend Framework Sessions Being Lost

I'm using sessions to store items in a shopping cart. I can create and persist sessions, but with some strange problems:
When I close the tab in Firefox (not the entire browser), the session appears to have been lost. Sometimes it doesn't happen though but usually it does.
Every single time I refresh the page or go to another page, the session ID changes to a new one. I've confirmed this by looking in the cookie with my browser, and also on the server. Also, there are a max of 4 sessions stored on the server at one time. Is all this normal behavior?
The sessions seem to be lost at random intervals...it could be a few minutes or more than an hour.
I just followed the Zend manual but no luck in solving any of this. In the bootstrap I also have Session::start() and Session::rememberMe(). I'm using normal file storage for sessions, just storing in /var/lib/php5 which I think is where Zend framework likes to put it.
Thanks for any direction
If the session data is persisting but the ID is changing then there is a chance there is a call to session_regenerate_id() in there somewhere.
I have run into this before, and you will want to do something like this where you start your session at, for me this is in my Bootstrap.php
if (!empty($_REQUEST['PHPSESSID'])) {
Zend_Session::setId($_REQUEST['PHPSESSID']);
}
Zend_Session::start();
This should solve the issue. When a user has a session, it typically gets passed with every request.
Check your garbage cleanup time for PHP - session.gc_maxlifetime. If it's short, it deletes your session files from under your nose and makes it appear "random".
The default value is 24 minutes (1440 seconds)
This should be set to (or greater than) whatever your cookie lifetime (session.cookie_lifetime) is set for in your application.

CodeIgniter is generating multiple sessions in the database. Why?

I have a site which does a few ajax calls on page load. For some reason, CodeIgnitor is inserting 4 sessions (I'm assuming one for each ajax call) as you load the page. I'm storing the sessions in the database.
I'm pretty sure there should only be one session per browser. Firefox seems to generate only one; other browsers seem to create a whole bunch of sessions. Multiple sessions for the same user are giving me some serious authentication problems.
Why is this happening? How can I stop it?
I know the discussion took place while ago, but somebody might find this useful.
By now I've used CI session without storing its data in database. Today I decided to give it a try and immediately run across the same problem: CI was generating new session in every page load.
I checked my server time, timezone, my cookie etc. - everything I could find as a tip on forums - with no result. Then decided to debug the CI Session class myself.
Long story short, it turned out that my user_agent field in my session table was too small - VARCHAR 50 - which cuts the original user_agent string - hence CI doesn't find my session and generates onother one. I just increased the user_agent field size to 200 and everything works like a charm.
I forgot to mention that I use Mac OS X Lion.
Again, hope this will help somebody.
Check the date / time on your client OS, and on your server.
I know its too late, but maybe someone finds this page while looking for the answer...
I think it happens because CI sets an expiration time on the cookie containing the session id and if the time difference between the server and client is higher than the expiration time the cookie gets old and the server will generate a new session for the client on every request. Never took the time to figure out the exact mechanism, but happened to me several times, and this fix always worked.
I've found this topic with same problem: on every page CI generates new session. Possible solution: remove underscored from site name ( NOT "my_test_site.com", but "my-test-site.com"). At least, this helped in my situation.
Check your config.php file and make sure the cookie options are properly filled out. If they are not it cant track the user and it will gen a new session on every page load.
Check the date / time on your client OS, and on your server.
I had the same situation and confirm the solution as a fix
$config['cookie_domain'] = "example.com";
Use your domain name in this snippet.

Safe timeout value for codeigniter session class?

I am using codeigniter's session class to handle my PHP sessions. One of the session variables automatically created on every visit to the site is session_id:
The user's unique Session ID (this is a statistically random string with very strong entropy, hashed with MD5 for portability, and regenerated (by default) every five minutes)
On my site I need to have functionality to track unregistered user's and I currently have this implemented by comparing the visitor's session_id with a stored id value in a VISITOR table in the database. This works perfectly except for the fact that the session id times out every five minutes. I would like my application to remember visitors for longer than 5 minutes (kind of like what SO does when you post a question or answer without registering).
My question is this: can you see any security issues with simply extending the regeneration time of the session class (to something like 12 hours)?
Update: based on the answers I've seen so far, it seems like its more of a performance concern rather than a safety issue. Its kinda weird how the codeigniter session class works because when creating a new session, it also creates a new cookie which seems to persist as long as the session. I guess I could create another cookie with the session ID that lasts as long as I need it to. But how much of a performance concern would it be if I were to save the sessions for something like 12 hours? Would it slow things down unless I have millions of unique visitors within a 12 hour period (in which case I'd have bigger problems to worry about...)?
Two things with that idea :
If users go away from their computer (without locking it / closing their browser), someone else might use it to go to your site with their account
well, that's probably not your problem
if you have some login/password fields, your users probably already have their login+password memorized by the browser anyway (well, for the registedred ones, anyway -- and those probably have more "power" than not registered ones)
If you have lots of users on your site, you will have more session files
as sessions are stored in files
(same if they are stored in DB / memcached -- in which case you must ensure you have configured memcached so there is enough RAM to store more sessions)
So, yes, there is a small security risk ; but I don't think it is really relevant.
Another idea would be to keep a short session lifetime, but to store some informations in cookies, with a lifetime more important than that ?
Enough information, actually, to allow re-creation of a new session, without the user noticing anything ?
But, yes, that would require a bit more work on your side...
To add a bit more precisions after your edit :
Its kinda weird how the codeigniter
session class works because when
creating a new session, it also
creates a new cookie which seems to
persist as long as the session.
This is the "standard" way of dealing with sessions -- at least, in PHP :
The session's data is stored in a file, on disk, on the server
and a cookie is used to keep a "link" between a user, and the file containing his session's information. Without that cookie, there would be no way of knowing which one of those files contains the session of a specific user.
But how much of a performance concern
would it be if I were to save the
sessions for something like 12 hours?
If you're having millions of users on your site, this will means having millions of files, each one containing the session's data of one user -- and it's not good to have too many files.
But is you are having a few hundreds user, that should be allright, I guess.
Depending on the amount of visitors to your site, saving sessions for 12 hours may not be a good idea. Why not use cookies? This is dependent on whether or not the user has it enabled in his browser though: http://www.php.net/setcookie.
One Security Tip:
Leave True on sess_match_useragent(application/config/config.php)

Categories