Home >PHP >PHP reference – functions >session_set_cookie_params

session_set_cookie_params

session_set_cookie_params($lifetime_or_options)

Sets the parameters of the cookie that carries the session ID. It applies to the current script and must be called before session_start(). Returns true, or false on failure.

Parameters

  • $lifetime_or_options – an array (from PHP 7.3) with the keys lifetime (lifetime in seconds, 0 = until the browser is closed), path, domain, secure, httponly and samesite. The older form has the parameters one after another: session_set_cookie_params($lifetime, $path, $domain, $secure, $httponly).

Examples

var_dump(session_set_cookie_params(array(
    "lifetime" => 0,
    "path" => "/",
    "secure" => true,
    "httponly" => true,
    "samesite" => "Lax",
))); // bool(true)
$p = session_get_cookie_params();
echo $p["samesite"]; // Lax
var_dump($p["httponly"]); // bool(true)
session_start();
// cannot be changed while the session is active (the notice is suppressed here with @)
var_dump(@session_set_cookie_params(array("lifetime" => 3600))); // bool(false)
session_destroy();

Things to watch out for

  • The setting applies only to the current script. Call it on every page before session_start(), ideally in a shared file. The same can be set permanently in php.ini (session.cookie_httponly…).
  • secure sends the cookie only over HTTPS. On a site without HTTPS the session would not work.
  • httponly prevents JavaScript from accessing the cookie, so a malicious script cannot steal it.
  • samesite Lax or Strict limits sending the cookie from other sites and protects against forged requests. None requires secure.
  • The cookie lifetime does not extend the life of the session data on the server. That is set by session.gc_maxlifetime.

Related functions:
session_start()
setcookie()
session_name()
session_get_cookie_params()