0

I'm having a hard time trying to parse response headers. Returned headers contain duplicate keys with the name of set-cookie which I'm trying to get along with the other headers but the problem is it overwrides the set-cookie value to the last one available. I know that we cannot have multiple name of the same key in an associative array, in that case what shuold I use to achieve this result?

[16] => set-cookie: GPS=1; Domain=.youtube.com; Expires=Sat, 14-Aug-2021 15:09:33 GMT; Path=/; Secure; HttpOnly
[17] => set-cookie: YSC=HYwhlVWBBfQ; Domain=.youtube.com; Path=/; Secure; HttpOnly; SameSite=none
[18] => set-cookie: VISITOR_INFO1_LIVE=E2nuslFFVxI; Domain=.youtube.com; Expires=Thu, 10-Feb-2022 14:39:33 GMT; Path=/; Secure; HttpOnly; SameSite=none

The script goes on forever if I include the while statement and if I remove it, it works fine but returning only the last set-cookie which is 18

$url = "https://www.youtube.com";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_NOBODY, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($curl);
curl_close($curl);
$h = array_filter(explode("\n", $resp), 'trim');
$headers = [];
foreach ($h as $k => $v) {
    $l = explode(": ", $v); // Desired keys values here.
    if (strpos($v, 'HTTP') == true) {
        $headers['Headers']['status'] = $l[0];
    } elseif (strpos($v, 'set-cookie') !== false) {
        // $headers['Headers']['Cookies'][]['set-cookie'] = $l[1]; Works but return each cookie as array
        while (str_contains($v, 'set-cookie')) {
            $headers['Headers']['set-cookie'] = $l[1];
        }
    } else {
        $headers['Headers'][$l[0]] = $l[1];
    }
}

1 Answer 1

1

The reason you get an array using the code below is that you are exploding the header keys using : which it is also available in the content of cookie values.

You can implode the initial exploded array from index 1 and it should work fine, so the code would be:

$headers['Headers']['Cookies'][]['set-cookie'] = implode(':', array_slice($l, 1));

Another solution is that you replace the set-cookie: with empty string and use it.

$headers['Headers']['Cookies'][]['set-cookie'] = str_replace("set-cookie:",'', $v);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.