You can set these parameters also with session_set_cookie_params
before you start the session with session_start
.
Here is the a part/the start of my php session class which sets some parameters automatically to the right value and others to some defaults. You can change these by overriding them with the parameter $moreoptions
.
class Session {
/**
* The flag to define if we work under SSL
* @var bool
* @access private
*/
private static bool $IS_SSL;
/**
* The session cookie parameters
* @var array<string,mixed>
* @access private
*/
private static array $cookieparams = array('lifetime' => 86400,
'path' => '/',
'httponly' => true,
'samesite' => 'Strict');
/**
* Starts the session with session_start()
*
* Note: If the session already has started nothing will happen
* @param array<string,mixed> $moreoptions Optional: Array with cookie params to overrule the defaults
* @param string $sessionname Optional: Another name for the session
* @return void
* @access public
*/
public static function start(array $moreoptions = array(), string $sessionname = '') : void {
if (!self::hasStarted()) {
self::$IS_SSL = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
if (!empty($sessionname)) {
session_name($sessionname);
} elseif (self::$IS_SSL) {
session_name('__Secure-PHPSESSID');
}
self::$cookieparams['domain'] = $_SERVER['SERVER_NAME'];
self::$cookieparams['secure'] = self::$IS_SSL;
session_set_cookie_params(array_merge(self::$cookieparams, $moreoptions));
session_start();
}
}
/**
* Tests if a session was started
* @return bool True if a session is running
* @access public
*/
public static function hasStarted() : bool {
return session_status() === PHP_SESSION_ACTIVE;
}
}