編譯以下函數能夠處理多個具有相同字段名稱的頭字段並將它們組合起來as stipulated by the specification:
Multiple message-header fields with the same field-name MAY be present in a message if and only if the entire field-value for that header field is defined as a comma-separated list [i.e., #(values)]. It MUST be possible to combine the multiple header fields into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field-value to the first, each separated by a comma.
function getHeaderFields() {
$fields = array();
$index = array();
foreach (headers_list() as $field) {
list($name, $value) = explode(':', $field, 2);
$name = trim($name);
if (isset($index[strtolower($name)])) {
$name = $index[strtolower($name)];
} else {
$index[strtolower($name)] = $name;
}
if (isset($fields[$name])) {
$fields[$name] .= ', '.trim($value);
} else {
$fields[$name] = trim($value);
}
}
return $fields;
}
這個工作在相反apache_response_headers
或其他提到的解決方案:
setcookie('foo', 'bar');
setcookie('bar', 'quux');
$headers = getHeaderFields();
var_dump($headers['Set-Cookie']); // string(17) "foo=bar, bar=quux"
$headers = apache_response_headers();
var_dump($headers['Set-Cookie']); // string(8) "bar=quux"
你打我,就像2秒! – JakeParis 2010-12-17 22:43:17
最重要的不是速度,而是質量:) – s3v3n 2010-12-17 22:44:23
將調用保存到trim()並以「:」爆炸會更快。略。 – JakeParis 2010-12-17 22:50:10