+add a note
User Contributed Notes 20 notes
final dot wharf at gmail dot com ¶
14 years ago
As PHP's Session Control does not handle session lifetimes correctly when using session_set_cookie_params(), we need to do something in order to change the session expiry time every time the user visits our site. So, here's the problem.
<?php
$lifetime=600;
session_set_cookie_params($lifetime);
session_start();
?>
This code doesn't change the lifetime of the session when the user gets back at our site or refreshes the page. The session WILL expire after $lifetime seconds, no matter how many times the user requests the page. So we just overwrite the session cookie as follows:
<?php
$lifetime=600;
session_start();
setcookie(session_name(),session_id(),time()+$lifetime);
?>
And now we have the same session cookie with the lifetime set to the proper value.
frank at frankforte dot ca ¶
4 years ago
The following appears to work for setting the SameSite attribute on session cookies for PHP < 7.3.
<?php
$secure = true; // if you only want to receive the cookie over HTTPS
$httponly = true; // prevent JavaScript access to session cookie
$samesite = 'lax';
if(PHP_VERSION_ID < 70300) {
session_set_cookie_params($maxlifetime, '/; samesite='.$samesite, $_SERVER['HTTP_HOST'], $secure, $httponly);
} else {
session_set_cookie_params([
'lifetime' => $maxlifetime,
'path' => '/',
'domain' => $_SERVER['HTTP_HOST'],
'secure' => $secure,
'httponly' => $httponly,
'samesite' => $samesite
]);
}
?>
theking2(at)king.ma ¶
1 year ago
As per version PHP 7 session_start can include an option array this function became obsolete. All cookie settings (and many more) can be included in an option array as a parameter to session_start():
<?php
session_start( [
'cookie_path' => '/',
'cookie_lifetime' => 300,
'cookie_secure' => true,
'cookie_httponly' => true,
'cookie_samesite' => 'lax',
] );
passerbyxp at gmail dot com ¶
12 years ago
One might want to be noted that the browsers are case-sensitive to the $path parameter.
For example, if you do this:
<?php
session_set_cookie_params(0,"/webapp/");
session_start();
?>
and you visit your site in this way:
example.com/WebApp/
You would get a new session on every request.
I'm not sure if this is the standard, but I see this happens on IE 6, Firefox 12 (Palemoon, actually), Chrome 19 (Portable version), and on both IIS and Apache.
Danack dot Ackroyd at gmail dot com ¶
13 years ago
Setting the domain for cookies in session_set_cookie_params() only affects the domain used for the session cookie which is set by PHP.
All other cookies set by calling the function setcookie() either:
i) Use the domain set explicitly in the call to setcookie()
or
ii) Don't set the domain at all on the cookie and so the browser assumes it's for the current domain.
So to make all your cookies be available across all sub-domains of your site you need to do this:
<?php
$currentCookieParams = session_get_cookie_params();
$rootDomain = '.example.com';
session_set_cookie_params(
$currentCookieParams["lifetime"],
$currentCookieParams["path"],
$rootDomain,
$currentCookieParams["secure"],
$currentCookieParams["httponly"]
);
session_name('mysessionname');
session_start();
setcookie($cookieName, $cookieValue, time() + 3600, '/', $rootDomain);
?>
shrockc at inhsNO dot SPAMorg ¶
22 years ago
when setting the path that the cookie is valid for, always remember to have that trailing '/'.
CORRECT:
session_set_cookie_params (0, '/yourpath/');
INCORRECT:
session_set_cookie_params (0, '/yourpath');
no comment on how long it took me to realize that this was the cause of my authentication/session problems...
werner dot avenant at gmail dot com ¶
12 years ago
Please take note of the garbage collection "feature" on systems like Ubuntu and Debian.
apt-get installs a cron script at /etc/cron.d/php5 that checks the session.gc_maxlifetime variable and then deletes all old sessions every 9 and 39 minutes.
The problem is: If you set the maxlifetime for a specific virtual host, those settings will be ignored. Lets say you want your server to store sessions for only 30 minutes, but for one special website you want all sessions to be 24 hours. If you set the session.gc_maxlifetime in .htaccess, your apache conf or use ini_set in your code, it won't work and sessions will still be destroyed after 30 minutes. That's because /usr/lib/php5/maxlifetime (found in that cron file) will always return the value in your php.ini, not the values you set in .htaccess.
A workaround is to set the maxlifetime to the maximum your sites require, and then configure a shorter maxlifetime in your .htaccess for those sites that don't need it.
Another solution is to give the php5 file in /etc/cron.d sane values, ie, only let it run at 3am in the morning, but you'll have to remember to block the replacement of this file it every time you update php.
Miki ¶
15 years ago
REMEMBER, that if you have a multi-subdomain site, you must put the following to enable a session id on the whole website:
<?php
session_set_cookie_params(0, '/', '.example.com');
session_start();
?>
Otherwise, you'll have 2 diffrent sessions on e.g. news.example.com and download.example.com
jordi at jcanals dot net ¶
20 years ago
Something that has taken me some time to debug: session_set_cookie_params() does not work when the domain param is just a one level domain, like it was a TLD.
I have a site in an intranet and our internal domain is .local, so trying to set the cookie session to the .local domain does not work:
session_set_cookie_params(0, '/', '.local'); // Does not work
In all test I've done, setting the domain only works for SLDs and above:
session_set_cookie_params(0 , '/', '.sld.local'); Does work
This is nothing to do with PHP but the http protocol, witch does not permit setting cookies for TLDs for obvious security reasons.
dan at vespernet dot co dot uk ¶
17 years ago
The below note is an excellent example of how to 'reset' the session expiration time upon a page refresh.
However, take care to compensate for when the session expires and doesn't renew itself (a bug I believe). If the below example is run every time a script is executed, it will give an 'Undefined index <session name> error' after the session fails to renew. Precede it with and if isset() condition.
<?php
private function startSession($time = 3600, $ses = 'MYSES') {
session_set_cookie_params($time);
session_name($ses);
session_start();
// Reset the expiration time upon page load
if (isset($_COOKIE[$ses]))
setcookie($ses, $_COOKIE[$ses], time() + $time, "/");
}
?>
The above example states that a session will last an hour without a page refresh until it is scrapped. Upon a page refresh, the expiration time is reset back to one hour again. If you wish to give users the option of 'staying logged in forever', just feed startSession a value of '99999999', which should last about 3 years.
Anonymous ¶
16 years ago
In Response to RC
>23-Apr-2008 04:45
>For anyone looking for which browsers support the HTTPOnly >flag, per my research:
>
>IE 6 SP 1 and higher.
>Firefox 3 and higher.
>Opera 9.50 and higher.
Firefox 2.0 also supports them, but only since version 2.0.0.5.
http://bugzilla.mozilla.org/show_bug.cgi?id=178993
theking2(at)king.ma ¶
9 months ago
For complete session cookie control I use this snippit
<?php
session_set_cookie_params( [
'lifetime' => 0,
'path' => '/',
'domain' => $_SERVER['HTTP_HOST'],
'samesite' => 'Strict',
] );
session_start( [
'name' => 'SESSION',
'sid_length' => 96,
'sid_bits_per_character' => 6,
'use_strict_mode' => true,
'referer_check' => $_SERVER['HTTP_HOST'],
] );
?>
This will set the params to the recommended ones and generates a cookie id of reasonable quality.
eion at robbmob dot com ¶
3 years ago
Unfortunately session_set_cookie_params() cannot be called during an active session, it'll just E_WARNING and return false, which means calling session_regenerate_id() (eg, during login to prevent a session fixation attack) could end up using old cookie settings (eg, not "SameSite=Strict")
To ensure any future sessions are being created with the right cookie settings, you're better off to use ini_set() to set the cookie parameters - which is all that session_set_cookie_params() does under the hood anyway
jan at dewal dot net ¶
14 years ago
The information above about this function that it can only be used BEFORE session_start depends on how you use it. Because its also useful AFTER a session has started as follows:
Example you wand to change an already set value of the session cookie expire time:
<?php
// Here we start as usual
session_set_cookie_params('3600'); // 1 hour
session_start();
// More code...
// Now we found in some database that the user whishes
// the cookie to expire after for example 10 minutes
// we can change it instantly !
session_set_cookie_params('600'); // 10 minutes.
session_regenerate_id(true);
// This will delete old cookie and adopt new expire settings and the
// old cookie variables in a new cookie
?>
Please note i only explained the browser (client) side changes of session cookie's expire time.