I've created the following function that creates a cookie string for passing to cURL. It can take a nested array or object of key-value pairs. It can either create nested cookie values as JSON, or using square brackets in cookie names.
Please could someone kindly:
- Assess whether it's functionally correct or not, does it generate good cookies? I don't know if it's necessary for it to repeat the expires/domain/path/secure/httponly for each cookie.
- Help reduce the bloat. I don't like how:
(a) it calls itself 3 times.
(b) it has the following code twice:
$keyPrefix?$keyPrefix."[".$key."]":$key
(c) in the middle, it checks:if (is_object($val) || is_array($val))
- it seems a bit redundant.
The function:
function http_build_cookie($data, $useJson=true, $expires = 0, $path = '', $domain = '', $secure = false, $httpOnly = false, $keyPrefix = '') {
if (is_object($data)) {
$data = (array) $data;
}
if (is_array($data)) {
$cookie_parts = array();
foreach ($data as $key => $val) {
if ($useJson)
{
$cookie_parts[] = http_build_cookie(
rawurlencode($key)."="
.rawurlencode(json_encode($val)),
$useJson, $expires, $path, $domain, $secure, $httpOnly
);
}
else
{
if (is_object($val) || is_array($val)) {
$cookie_parts[] = http_build_cookie(
$val, $useJson, $expires, $path, $domain,
$secure, $httpOnly, $keyPrefix?$keyPrefix."[".$key."]":$key
);
}
else
{
$cookie_parts[] = http_build_cookie(
rawurlencode($keyPrefix?$keyPrefix."[".$key."]":$key)."="
.rawurlencode($val),
$useJson, $expires, $path, $domain, $secure, $httpOnly
);
}
}
}
return implode('; ', $cookie_parts);
}
if (is_scalar($data)) {
$cookie = $data;
if ($expires) {
$cookie .= '; expires=' . gmdate('D, d-M-Y H:i:s T', $expires);
}
if ($path) {
$cookie .= '; path=' . $path;
}
if ($domain) {
$cookie .= '; domain=' . $domain;
}
if ($secure) {
$cookie .= '; secure';
}
if ($httpOnly) {
$cookie .= '; HttpOnly';
}
return $cookie;
}
return '';
}
Any advice would be massively appreciated!