CodeIgniter 4 Session is destroyed after refreshing the website - codeigniter

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:
But when I refresh the page, the session has gone:

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

Related

laravel 6 csrf token expired in every 60 seconds?

I am using laravel 6.I Want my laravel CSRF Token expire in every 60 seconds.
config/session
'lifetime' => 60,
First of All, CSRF is stored in XSRF-TOKEN cookie. Ref: 50904763
According to the question (Ref: 51615122), We change the configuration in app/Http/Middleware/VerifyCsrfToken.php by adding a new method named addCookieToResponse
use Symfony\Component\HttpFoundation\Cookie;
public function addCookieToResponse($request, $response) {
$config = config('session');
$session_life = env('CSRF_LIFE');
$response->headers->setCookie(
new Cookie(
'XSRF-TOKEN', $request->session()->token(), $this->availableAt($session_life),
$config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null
)
);
}
where $config is used to get session information from existing lifetime. However, I parse $session_life from .env to make sure you can customize as much as you can.
So, the result is simple, configure everything as belongs but in area $this->availableAt($session_life) where session_life is in seconds.
So, please set session_life to 60 in .env as below:
CSRF_LIFE="60"
After you save and refresh your page, or clean cache and configs, Session LifeTime will be two hours but CSRF will be only 60 secs.
Hope this works.
After long testing I end up something, that you put in the lifetime option in session not allow to set expire time in seconds, it'll allow to minutes.
So, when you set up liftime = "60", it's means it will expire in 1 hour.
Hence, You have to set liftime = "1" in your config/session.pph file. Also, default value in .env file SESSION_LIFETIME=120 you have to replace that with 1 SESSION_LIFETIME = 1.
After that you have to clear the cache by command:-
php artisan config:cache
Now, your session will expire after 1 minute / 60 seconds.
To see more check this question.

php - i am getting logged out after being idle

I do not want the user to be logged out of the site even if the person is idle for, it is okay if the person is logged out if he has closed the browser.
session.gc_maxlifetime = 180000
session.gc_probability = 1
session.gc_divisor = 1
session.save_path = "/var/lib/php/session"
cookie_lifetime = 0
Is there any setting that i am missing?
Please help
To set the life time i have added the following code.
session_set_cookie_params(21600);
session_start();
You need extend your live time of cookie, remember that session id is stored in user webbrowser within cookie, set session.cookie_lifetime with a more big value too.
session_set_cookie_params(21600);
session_start();
21600 seconds is only 6 hours
Try setting to something bigger maybe even PHP_INT_MAX
Dont know whether it will help just wrote to give u the idea of how?....cookie are saved at user browser so ,
$cookieName = "userscookie";
$lifetime = time() + (60*60*24); // one day life
if(isset($_COOKIE[$cookieName])) {
$value = $_COOKIE[$cookieName];
// one day life from day of access
setcookie($cookieName, $value, $lifetime);
} else {
$value = "this value to store";
setcookie($cookieName, $value, $lifetime);
}
output:
Thankyou

Codeigniter creates new session row with same userdata

I'm working on a large-scale web app in Codeigniter with HMVC modular extensions and having problems with sessions whilst using the database (to store the sessions).
My sessions are being lost for a reason I can simply not understand.
A prime example is using the Codeigniter cart. I can successfully add items to my cart and click around the site with the items remaining in the session. However, when clicking around/pause navigating the website for ~ 3 minutes (not timed to the second) the cart losses all it's products and the session is empty. When reviewing the database, the old session is still stored in the database with the content but with a new session row created (as below).
I'm running the latest version of Codeigniter with no extensions to the original Session.php class.
Below are my session config variables:
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_cookie_name' = the name you want for the cookie
| 'sess_expiration' = the number of SECONDS you want the session to last.
| by default sessions last 7200 seconds (two hours). Set to zero for no expiration.
| 'sess_expire_on_close' = Whether to cause the session to expire automatically
| when the browser window is closed
| 'sess_encrypt_cookie' = Whether to encrypt the cookie
| 'sess_use_database' = Whether to save the session data to a database
| 'sess_table_name' = The name of the session database table
| 'sess_match_ip' = Whether to match the user's IP address when reading the session data
| 'sess_match_useragent' = Whether to match the User Agent when reading the session data
| 'sess_time_to_update' = how many seconds between CI refreshing Session Information
|
*/
$config['sess_cookie_name'] = 'myhmvc_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'users_sessions';
$config['sess_match_ip'] = TRUE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookies will only be set if a secure HTTPS connection exists.
|
*/
$config['cookie_prefix'] = "my";
$config['cookie_domain'] = "myhmvc.co.uk";
$config['cookie_path'] = "/";
$config['cookie_secure'] = FALSE;
Any help is greatly appreciated, willing to try anything at this stage.
I've still not gotten round to understanding Codeigniter's issue with sessions but from reading other posts there's quite an issue with default sessions.
I've installed the Session Driver seen here:
http://getsparks.org/packages/session-driver/versions/HEAD/show
Which has now fixed the issue.
I hope this helps others who have had similar problems.

file based caching in codeigniter

I am new to codeigniter. I want to use file-based caching.I don't know if I understood correctly.
1. Declare the following in the parent controller --$this->load->driver('cache');
2. $this->cache->file->save('foo', 'bar', 10); is used to save the file but i don't know what are the parameters of this function and how to implement all these so that caching can be done.
Please help
http://codeigniter.com/user_guide/libraries/caching.html#example_usage
The manual has it - but it's a bit hidden in the example:
if ( ! $foo = $this->cache->get('foo'))
{
echo 'Saving to the cache!<br />';
$foo = 'foobarbaz!';
// Save into the cache for 5 minutes
$this->cache->save('foo', $foo, 300);
}
'foo' -> the name for the variable you're about to cache
$foo -> the variable to cache. It can be anything
300 -> time in seconds (60*5) - set to 0 for no expiry
So IF $foo is empty the cache file is recreated, else you can use $foo to load data.
Further notes:
http://codeigniter.com/user_guide/general/caching.html
A more flexible alternative could be this sparks library:
http://getsparks.org/packages/cache/show
I use it and it fits my needs for file-based caching very well.

Opencart cart across multiple stores with different subdomains

Hi have a single opencart install setup with several stores with different subdomains (all under the same domain). I want customers to be able to put items in the cart on one site, then move onto the next and put in more or even subtract, till eventually a customer checkouts out on any store. Note products might appear in one store but not another.
I notice opencart does this somewhat. ie it will bring products already in the cart to the next store but only if the products appear in both stores. Further if a customer then deletes one of the items and moves back to the same store, they product reappears.
First Problem seems to firstly be products in the cart are being displayed through what i guess is a query that selects products by store_id. I have had a hard look to see if i can find anything but am at a loss.
Second problem seems to be with the contents of the session. I am still learning php and am a bit confused of how to even attempt to modify how the session works.
Can anyone please provide some guidance on how i can go about fixing/changing this.
OpenCart stores all these information in you PHP session. Since your stores are located under different subdomains, the PHP session changes when you switch from one store to another.
So the first thing you need to do is to share the session between all subdomains. By default, PHP uses the 'PHPSESSID' cookie to propagate session data across multiple pages, and by default it uses the current top-level domain and subdomain in the cookie declaration.
Example: www.domain.com
The downside to this is that the session data can't travel with you to other subdomains. So if you started a session on www.domain.com, the session data would become unavailable on forums.domain.com. The solution is to change the domain PHP uses when it sets the 'PHPSESSID' cookie.
Assuming you have an init file that you include at the top of every PHP page, you can use the ini_set() function. Just add this to the top of your init page:
ini_set('session.cookie_domain',
substr($_SERVER['SERVER_NAME'],strpos($_SERVER['SERVER_NAME'],"."),100));
This line of code takes the domain and lops off the subdomain.
Example: forums.domain.com -> .domain.com
Now, every time PHP sets the 'PHPSESSID' cookie, the cookie will be available to all subdomains!
You might also need to make some little modifications to the OpenCart's core in order to make it work.
Have fun :)
After Tohids help I have the following solution, hopefully it helps others. I added the cookie_domain code line to the session.php file and also added or changed the cookie name wherever the setcookie function was used to cover the currency and language cookies.
open \system\session.php
find;
ini_set('session.use_cookies', 'On');
ini_set('session.use_trans_sid', 'Off');
insert after;
ini_set('session.cookie_domain', substr($_SERVER['SERVER_NAME'],strpos($_SERVER['SERVER_NAME'],"."),100));
open \index.php
find;
if (!isset($request->cookie['language']) || $request->cookie['language'] != $code) {
setcookie('language', $code, time() + 60 * 60 * 24 * 30, '/', $request->server['HTTP_HOST']);
}
replace with;
if (!isset($request->cookie['language']) || $request->cookie['language'] != $code) {
setcookie('language', $code, time() + 60 * 60 * 24 * 30, '/', substr($_SERVER['SERVER_NAME'],strpos($_SERVER['SERVER_NAME'],"."),100));
}
find;
if (isset($request->get['tracking']) && !isset($request->cookie['tracking'])) {
setcookie('tracking', $request->get['tracking'], time() + 3600 * 24 * 1000, '/');
}
replace with;
if (isset($request->get['tracking']) && !isset($request->cookie['tracking'])) {
setcookie('tracking', $request->get['tracking'], time() + 3600 * 24 * 1000, '/', substr($_SERVER['SERVER_NAME'],strpos($_SERVER['SERVER_NAME'],"."),100));
}
open system\currency.php
find;
if (!isset($this->request->cookie['currency']) || ($this->request->cookie['currency'] != $currency)) {
setcookie('currency', $currency, time() + 60 * 60 * 24 * 30, '/', $this->request->server['HTTP_HOST']);
}
replace with;
if (!isset($this->request->cookie['currency']) || ($this->request->cookie['currency'] != $currency)) {
setcookie('currency', $currency, time() + 60 * 60 * 24 * 30, '/', substr($_SERVER['SERVER_NAME'],strpos($_SERVER['SERVER_NAME'],"."),100));
}
Very Easy Solution! Share the login session across the subdomains
OPEN FILE: system/library/session.php
FIND LINE: session_set_cookie_params(0, '/');
APPEND : session_set_cookie_params(0, '/','.DOMAIN.COM);
Make sure to include the period "." before DOMAIN.COM
That's it... Now login sessions started on www.domain.com is shared with www.sub.domain.com

Resources