note 118892 added to function.http-parse-headers

From: Date: Tue, 23 Feb 2016 19:31:50 +0000
Subject: note 118892 added to function.http-parse-headers
Groups: php.notes 
Request: Send a blank email to php-notes+get-205024@lists.php.net to get a copy of this message
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) ?> ---- Server IP: 72.52.91.14 Probable Submitter: 178.20.159.9 ---- Manual Page -- http://php.net/manual/en/function.http-parse-headers.php Edit -- https://master.php.net/note/edit/118892 Del: integrated -- https://master.php.net/note/delete/118892/integrated Del: useless -- https://master.php.net/note/delete/118892/useless Del: bad code -- https://master.php.net/note/delete/118892/bad+code Del: spam -- https://master.php.net/note/delete/118892/spam Del: non-english -- https://master.php.net/note/delete/118892/non-english Del: in docs -- https://master.php.net/note/delete/118892/in+docs Del: other reasons-- https://master.php.net/note/delete/118892 Reject -- https://master.php.net/note/reject/118892 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#205024) next »