I have two questions to ask, on the same topic.
In a new server (debian 10) whith standard parameters in php.ini (7.4) and standard apache2 configurations, the following code doesn’t work.
session_name('mySiteSession');
session_start();
$params = [
'lifetime' => time()+600,
'path' => '/crm',
'domain' => $_SERVER['HTTP_HOST'],
'secure' => 0,
'httponly' => 0,
'samesite' => 'Strict'
];
setcookie(session_name(), session_id(), $params["lifetime"], $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
The cookie correctly set only the name, path and domain parameter, the others remain false and none.
This is the first part of the problem, the second part, I tried with the parameters in session_start
session_name('mySiteSession');
$session_options = [
'cookie_lifetime' => time()+600,
'cookie_path' => '/crm',
'cookie_domain' => $_SERVER['HTTP_HOST'],
'cookie_secure' => 0,
'cookie_samesite' => 'Strict',
'cookie_httponly' => 1,
'read_and_close' => true
];
session_start($session_options);
set the cookies correctly but the session does not start and if I repeat session_start () without parameters
Notice: session_start (): A session had already been started –
ignoring…
but
var_dump($_SESSION) is void.
Best regards
2
Answers
You have to do
session_start()
on the very first line of your file. I think that that is your issue.I had exactly the same problem, even if I had set
session_start()
andsetcookie(...)
directly at the beginning of the script. A new session was started with every call because the cookie was not set.The solution for me was now
session_cookie_params(...)
first, followed bysession_start()
.session_cookie_params
hast to be called beforesession_start
!Read about session_cookie_params() on php.net for further details on parameters and notation.
Attention: in my case, ‘secure’ must be set to false to work properly on local testing! Don’t forget to switch true when going into production. Domain defaults to current.
This cookie will expire after the lifetime in seconds no matter how often the person comes back in the meantime. If you want your cookie to refresh automatically on every visit, you can do this like this:
If this still does not fix it for you, you can try to buffer each output (which probably sent headers before your session settings) and locate the problem. See
ob_start
(on php.net) andob_get_clean
(on php.net) for example.