note 118892 deleted from function.http-parse-headers by sobak
| From: | sobak@php.net | Date: | Sun, 04 Dec 2016 07:22:44 +0000 |
| Subject: | note 118892 deleted from function.http-parse-headers by sobak | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208068@lists.php.net to get a copy of this message | ||
Note Submitter: cttr dot web at gmail dot com
----
Hi. Rewrote a function below comments
Github: https://github.com/mr-cttr/http_parse_headers
<?php
$headers = "content-type: text/html; charset=UTF-8\r\n".
"Server: Nginx\r\n".
"set-cookie: user=\r\n\tunknown\r\n".
"set-cookie: pass=strong\r\n\tpassword\r\n".
"Set-Cookie: id=1\r\n".
"HOST:github.com";
http_parse_headers ($headers);
function http_parse_headers ($raw)
{
$k = '';
$out = [];
$exp = explode("\n", $raw);
foreach ($exp as $v) {
$exp = explode(':', $v, 2);
if (isset($exp[1])) {
/** Сonvert to 'Word-Word' */
$k = strtolower($exp[0]);
$k = preg_replace_callback('/\b[a-z]/', function ($m) { return
strtoupper($m[0]); }, $k);
$value = trim($exp[1]);
if (!isset($out[$k])) $out[$k] = []; /** for in_array */
if (!in_array($value, $out[$k])) $out[$k][] = $value; /** New element in array */
} else {
$value = trim($exp[0]);
if (!empty($exp[0][0]) && $exp[0][0] == "\t") {
/** Index last element */
end($out[$k]);
$i = key($out[$k]);
$out[$k][$i] .= "\r\n\t". $value;
} elseif (!$k)
$out[0] = $value;
}
}
/** Array has only once element - convert in string */
$out = array_map(function ($v) { return count($v) < 2 ? $v[0] : $v; }, $out);
return $out;
}
?>
Old function output with error
<?php
array (size=5)
'content-type' => string 'text/html; charset=UTF-8' (length=24)
'Server' => string 'Nginx' (length=5)
'set-cookie' => string 'Array // Notice: Array to string conversion
password' (length=16)
'Set-Cookie' => string 'id=1' (length=4)
'HOST' => string 'github.com' (length=10)
?>
My function output
<?php
array (size=4)
'Content-Type' => string 'text/html; charset=UTF-8' (length=24)
'Server' => string 'Nginx' (length=5)
'Set-Cookie' =>
array (size=3)
0 => string 'user=
unknown' (length=15)
1 => string 'pass=strong
password' (length=22)
2 => string 'id=1' (length=4)
'Host' => string 'github.com' (length=10)
?>