M. Fahril Pratama
M. Fahril Pratama

Reputation: 21

CodeIgniter 4 Session is destroyed after refreshing the website

My session is always destroyed after refreshing the page.

This is my setting.

app.sessionDriver = 'CodeIgniter\Session\Handlers\DatabaseHandler'
app.sessionCookieName = 'sippeg_session'
app.sessionExpiration = 0
app.sessionSavePath = 'ci_sessions'
app.sessionMatchIP = false
app.sessionTimeToUpdate = 300
app.sessionRegenerateDestroy = false

I don't have any code that leads to session_destroyed.

My session is still available before the redirect:

Entered Session Data To The Database.

But when I refresh the page, the session has gone:

The Session Data Is Gone.

Upvotes: 2

Views: 1696

Answers (1)

steven7mwesigwa
steven7mwesigwa

Reputation: 6700

Explanation:

CodeIgniter 4 Session Preferences

If sessionExpiration is set to 0, the session.gc_maxlifetime setting set by PHP in session management will be used as-is (often the default value of 1440). This needs to be changed in php.ini or via ini_set() as needed.

Excerpt From The php.ini file (session.cookie_lifetime)

; Lifetime in seconds of cookie or, if 0, until browser is restarted.
; https://php.net/session.cookie-lifetime
session.cookie_lifetime = 0

Excerpt From The php.ini file (session.gc-maxlifetime)


; After this number of seconds, stored data will be seen as 'garbage' and
; cleaned up by the garbage collection process.
; https://php.net/session.gc-maxlifetime
session.gc_maxlifetime = 1440

; NOTE: If you are using the subdirectory option for storing session files
;       (see session.save_path above), then garbage collection does *not*
;       happen automatically.  You will need to do your own garbage
;       collection through a shell script, cron entry, or some other method.
;       For example, the following script is the equivalent of setting
;       session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes):
;          find /path/to/sessions -cmin +24 -type f | xargs rm

Solution:

Based on the fact that you normally don't have access to the php.ini file on shared web hosting services to configure the session.gc_maxlifetime, it would be more convenient to set that directly in the .env file at the root path of your project. I.e:

Instead of:

app.sessionExpiration = 0 ❌

Use this:

The time is measured in seconds. 86400 = 24 hours.

app.sessionExpiration = 86400 ✅
cookie.expires = 86400

Upvotes: 1

Related Questions