PHP sessions timing out too quickly
Asked Answered
U

4

39

I'm using php Sessions on my website and it seems like they are "disappearing" at random intervals. I don't know if they are timing out due to inactivity or if something is wrong with my code, but is there some way to control the sessions of when they expire?

Like can I put something in my code or change something in the php.ini file?

Update- So just and update here, I switched hosts and magically the sessions started working. I have no clue what was wrong but apparently they did not want to work correctly.

Unsure answered 13/8, 2010 at 11:55 Comment(7)
You'll find your answer here: #1516766Dumm
That was awesome thanks. It was actually this that ended up being extremely helpful: #520737Unsure
That was even more awesome, thanks :)Dumm
@TalviWatia - why do you despise using session variables? They are a necessity in PHP development.Marston
@TalviWatia - two years ago or 10. Sessions are requirements in 90%+ of PHP projects. You may as well have said you despise writing IF statements.Marston
@TalviWatia - Came across the OP question looking for something else and felt the need to point out a bad comment since I can't downvote like a bad answer. PHP Sessions can be cumbersome in a few ways but saying you despise them is absurd.Marston
There's an explanation for why switching hosts probably helped, together with a recipe for solving it no matter the host, in this answer: #8311820 - probably the first host was Debian- or Ubuntu-based, or did the same cron-based cleanup as they do.Abominate
C
50

Random expiration is a classical symptom of session data directory shared by several applications: the one with the shortest session.gc_maxlifetime time is likely to remove data from other applications. The reason:

  1. PHP stores session files in the system temporary directory by default.
  2. The builtin file handler doesn't track who owns what session file (it just matches file name with session ID):

    Nothing bug good old files

My advice is that you configure a private custom session directory for your application. That can be done with the session_save_path() function or setting the session.save_path configuration directive. Please check your framework's documentation for the precise details on how to do it in your own codebase.

Cohdwell answered 24/8, 2010 at 10:40 Comment(10)
Are you suggesting to insert this on every page?Marston
@Marston - Have a look at the include family of statements.Bratton
i understand include and requires. If the OP has hundreds or thousands of pages this would be a nightmare if not impossible. Find and replace is possible assuming all pages have some type of basic structure but still seems like a really strange way to go about it.Marston
@Marston - I can't understand your complaints. If the OP does not really have a centralised spot to set application-wide settings (and that's your hypothesis, he never said a word about that), that's a design issue totally unrelated to this question.Bratton
Not complaining at all - just don't know if this is the route I personally would have gone. I am not assuming he has full root access anymore than you are assuming that inserting 'include' statements wouldn't take him an incredible amount of time depending on how he currently has his pages developed is all.Marston
@Marston - I admit now I'm really curious about how you manage application-wide settings if include statements it not your route. You copy and paste the same values on every single file where it's needed?Bratton
As I stated the first time, just as your answer assumes he doesn't have full root access, I'll assume he does and only runs one application on this sever and say this can be managed easily by modifying the php.ini settings instead of having to modify every single file in the primary directory.Marston
@Marston This answer is fine. Having to "modify every single file in the primary directory" is a big assumption, and if you ever find yourself in that situation where a session config change requires you to do that, then you should learn how to structure a codebase. It's bad for everyone to think of answers in the assumption of poorly managed codebases.Lavella
@ÁlvaroGonzález that makes sense perhaps for a structural PHP application but those using OOP and PHP frameworks should not use this, take a look to this post #28240083 from my authority and let me know your toughs on thisTeshatesla
@Teshatesla Sorry but I'm tired of comments about an irrelevant bit of my answer that's shown for mere illustration purposes and however appears to be vastly misinterpreted. I'll edit it out ASAP.Bratton
M
17

Debian uses a cron job to automatically expire sessions in a secure manner. If you are using Debian, look at /etc/cron.d/php5.

Meek answered 28/8, 2010 at 19:55 Comment(1)
Ubuntu also has a /etc/cron.d/php which uses session.gc_maxlifetime in /etc/php/7.0/fpm/php.ini to remove sessions from /var/lib/php/sessions.Luigi
D
7

You can use it technique to make compatible your application according to you. You have to make few changes according to your system

// Get the current Session Timeout Value
$currentTimeoutInSecs = ini_get(’session.gc_maxlifetime’);

Change the Session Timeout Value

// Change the session timeout value to 30 minutes  // 8*60*60 = 8 hours
ini_set(’session.gc_maxlifetime’, 30*60);
//————————————————————————————–

// php.ini setting required for session timeout.

ini_set(‘session.gc_maxlifetime’,30);
ini_set(‘session.gc_probability’,1);
ini_set(‘session.gc_divisor’,1);

//if you want to change the  session.cookie_lifetime.
//This required in some common file because to get the session values in whole application we need to        write session_start();  to each file then only will get $_SESSION global variable values.

$sessionCookieExpireTime=8*60*60;
session_set_cookie_params($sessionCookieExpireTime);
session_start();

// Reset the expiration time upon page load //session_name() is default name of session PHPSESSID

if (isset($_COOKIE[session_name()]))
    setcookie(session_name(), $_COOKIE[session_name()], time() + $sessionCookieExpireTime, “/”);
    //————————————————————————————–
    //To get the session cookie set param values.

    $CookieInfo = session_get_cookie_params();

    echo “<pre>”;
    echo “Session information session_get_cookie_params function :: <br />”;
    print_r($CookieInfo);
    echo “</pre>”;
Damato answered 13/8, 2010 at 12:9 Comment(1)
It actually does. You're probably thinking of cookie expiration.Bratton
I
3

Try to use this part of code:

  session_start();
  $inactive = 600;
  $session_life = time() - $_SESSION['timeout'];
  if($session_life > $inactive) { 
     session_destroy(); 
     header("Location: logoutpage.php"); 
  }
  $_SESSION['timeout']=time();
Isolative answered 13/8, 2010 at 12:2 Comment(4)
Okay so I have a library php page that is included on every page of the site, I'm assuming whenever they log in I would start the session timeout. Would I use that bit of code in the library so that everytime they load a page it updates their activity?Unsure
This will destroy every session after 10mins of inactivity. Delete everything expect the first and the last line of this code and you'll have the real answer to the question.Dumm
And for the love of goodness, test the existence of variables before using them! Assuming $_SESSION['timeout'] to be valid is Bad(TM)Tympan
on the first run it will give you undefined index, you have to change line 3Flush

© 2022 - 2024 — McMap. All rights reserved.