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.

Adam Libuša
  • 685
  • 7
  • 24
jefffan24
  • 1,326
  • 3
  • 20
  • 35
  • 2
    You'll find your answer here: http://stackoverflow.com/questions/1516266/how-long-will-my-session-last/1516284 – svens Aug 13 '10 at 12:02
  • 2
    That was awesome thanks. It was actually this that ended up being extremely helpful: http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes/1270960#1270960 – jefffan24 Aug 13 '10 at 12:12
  • 1
    That was even more awesome, thanks :) – svens Aug 13 '10 at 12:18
  • @TalviWatia - why do you despise using session variables? They are a necessity in PHP development. – JM4 Feb 14 '13 at 17:57
  • 1
    @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. – JM4 Feb 15 '13 at 18:10
  • 1
    @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. – JM4 Feb 21 '13 at 21:40
  • 1
    There's an explanation for why switching hosts probably helped, together with a recipe for solving it no matter the host, in this answer: http://stackoverflow.com/questions/8311320/php-change-the-session-timeout/18573350#18573350 - probably the first host was Debian- or Ubuntu-based, or did the same cron-based cleanup as they do. – Pedro Gimeno Mar 22 '14 at 18:03

4 Answers4

49

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.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • Are you suggesting to insert this on every page? – JM4 Feb 07 '13 at 23:07
  • 5
    @JM4 - Have a look at the [include](http://php.net/include) family of statements. – Álvaro González Feb 08 '13 at 08:05
  • 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. – JM4 Feb 14 '13 at 17:50
  • @JM4 - 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. – Álvaro González Feb 14 '13 at 17:54
  • 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. – JM4 Feb 14 '13 at 17:58
  • @JM4 - 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? – Álvaro González Feb 14 '13 at 19:50
  • 2
    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. – JM4 Feb 14 '13 at 22:42
  • 12
    @JM4 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. – Alexander Apr 21 '13 at 07:43
  • @Á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 http://stackoverflow.com/questions/28239583/session-expires-even-if-im-working-session-lifetime-ajax-and-symfony2 from my authority and let me know your toughs on this – ReynierPM Apr 07 '16 at 13:15
  • 1
    @ReynierPM 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. – Álvaro González Apr 07 '16 at 14:07
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.

Docunext
  • 803
  • 6
  • 9
  • 2
    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`. –  Oct 20 '16 at 16:46
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>”;
halfer
  • 19,824
  • 17
  • 99
  • 186
Rubyist
  • 6,486
  • 10
  • 51
  • 86
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();
Alex Pliutau
  • 21,392
  • 27
  • 113
  • 143
  • 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? – jefffan24 Aug 13 '10 at 12:04
  • 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. – svens Aug 13 '10 at 12:06
  • 2
    And for the love of goodness, test the existence of variables before using them! Assuming $_SESSION['timeout'] to be valid is Bad(TM) – Fake51 Aug 13 '10 at 12:36
  • 1
    on the first run it will give you undefined index, you have to change line 3 – talsibony Dec 29 '15 at 07:06