Secure Cookie Options Builder
Builds consistent cookie settings for secure, HttpOnly, SameSite, and lifetime flags.
Function signature
ogBuildSecureCookieOptions(lifetime = 0, options = array())
Categories
- Security
Parameters
lifetimeCookie lifetime in seconds. Use 0 for session cookie.optionsOptional path, domain, secure, httponly, and samesite. Recognized keys: `domain`, `httponly`, `path`, `samesite`, `secure`.Return value
Short public-safe status message.
- options
Compatibility
Existing function name and call order preserved; metadata signature corrected to source.
Minimum PHP version: 7.4
Security notes
Validate request method, identity, permissions, and caller-owned allowlists before use; keep secrets out of public output.
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Builds secure cookie options for setcookie().
*
* The returned array uses PHP's modern setcookie options shape. Controllers on
* older runtimes can still read the same values and send headers manually.
*
* @param int $lifetime Cookie lifetime in seconds. Use 0 for session cookie.
* @param array $options Optional path, domain, secure, httponly, and samesite.
* @return array Secure cookie options.
*/
function ogBuildSecureCookieOptions($lifetime = 0, $options = array()) {
$result = array(
'success' => false,
'message' => '',
'data' => array()
);
$lifetime = (int)$lifetime;
if (!is_array($options)) {
$options = array();
}
$path = '/';
if (!empty($options['path'])) {
$path = (string)$options['path'];
}
if (substr($path, 0, 1) != '/') {
$path = '/';
}
$domain = '';
if (!empty($options['domain'])) {
$domain = trim((string)$options['domain']);
$domain = preg_replace('/^www\./i', '', $domain);
}
$same_site = 'Lax';
if (!empty($options['samesite'])) {
$same_site = ucfirst(strtolower((string)$options['samesite']));
}
if (!in_array($same_site, array('Lax', 'Strict', 'None'), true)) {
$same_site = 'Lax';
}
$secure = true;
if (isset($options['secure']) && $options['secure'] === false) {
$secure = false;
}
if ($same_site == 'None') {
$secure = true;
}
$http_only = true;
if (isset($options['httponly']) && $options['httponly'] === false) {
$http_only = false;
}
$cookie_options = array(
'expires' => 0,
'path' => $path,
'domain' => $domain,
'secure' => $secure,
'httponly' => $http_only,
'samesite' => $same_site
);
if ($lifetime > 0) {
$cookie_options['expires'] = time() + $lifetime;
}
$result['success'] = true;
$result['message'] = 'Secure cookie options built.';
$result['data'] = array('options' => $cookie_options);
return $result;
}