Answer the question
In order to leave comments, you need to log in
How to parse a complex header?
The request header contains rather complicated content:
X-CALLBACK-ID timestamp=1563105451261; nonce=a07bfa17;value=E4YeOsnMtHZ6592U8B9S37238E+Hwtjfrmpf8AQXF+c=
I want to parse this into an array
$aaa = [
'timestamp' =>1563105451261,
'nonce' =>'a07bfa17',
'value' =>'E4YeOsnMtHZ6592U8B9S37238E+Hwtjfrmpf8AQXF+c=',
];
public function handle($request, Closure $next)
{
$xHeader = $request->header("X-CALLBACK-ID");
if (!$xHeader) {
abort(403);
}
$kvPairs = explode(";", $xHeader);
if (count($kvPairs) != 3) {
abort(403);
}
$parsedHeader = [];
foreach ($kvPairs as $pair) {
$pos = strpos($pair, "=");
if (!$pos) {
abort(403);
}
$parsedHeader[substr($pair, 0, $pos)] = substr($pair, $pos + 1);
}
if (!isset($parsedHeader['timestamp'], $parsedHeader['nonce'], $parsedHeader['value'])) {
abort(403);
}
Answer the question
In order to leave comments, you need to log in
<?php
$xHeader = 'timestamp=1563105451261; nonce=a07bfa17;value=E4YeOsnMtHZ6592U8B9S37238E+Hwtjfrmpf8AQXF+c=';
preg_match_all('!([^=; ]+)=([^;]+)!si', $xHeader, $out);
$parsedHeader = array_combine($out[1], $out[2]);
print_r($parsedHeader);
Array
(
[timestamp] => 1563105451261
[nonce] => a07bfa17
[value] => E4YeOsnMtHZ6592U8B9S37238E+Hwtjfrmpf8AQXF+c=
)
Yes, it looks ok. You can replace foreach with array_map. It is considered good practice for a function to return a value. Also, doing abort(403) twice is not nice either. But the code is working, that's the main thing.
I still don’t see the use of the next input parameter in the code. Is he redundant? Well, then the laravel question tag is apparently superfluous.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question