D
D
di2021-06-24 09:30:30
PHP
di, 2021-06-24 09:30:30

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=',
        ];

In principle, I wrote a working solution, but it somehow looks dumb
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);
        }

Perhaps there is some more productive and readable solution? Please tell me if you know how to implement it better?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nokimaro, 2021-06-24
@nokimaro

<?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);

result
Array
(
    [timestamp] => 1563105451261
    [nonce] => a07bfa17
    [value] => E4YeOsnMtHZ6592U8B9S37238E+Hwtjfrmpf8AQXF+c=
)

A
Anton, 2021-06-24
@karminski

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 question

Ask a Question

731 491 924 answers to any question