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];
}
}