How to set multiple cookies by using php header

Viewed 1236

when a php header() function is used to set multiple cookies, only the last cookie works. All other cookie set attempts before are discarded. For example:

header("Set-Cookie: cookie1=fox; expires=Mon, 28-Sep-20 10:24:49 GMT; path=/");
header("Set-Cookie: cookie2=fish; expires=Mon, 28-Sep-20 10:24:49 GMT; path=/");

only cookie2 is set here. How can i set several cookies successfully by using header() method?

(header method also discards the setcookie functions sent before)

2 Answers

Use the second argument to false

header

(PHP 4, PHP 5, PHP 7, PHP 8) header — Send a raw HTTP header

Description

header(string $header, bool $replace = true);

$replace

The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in false as the second argument you can force multiple headers of the same type. For example:

<?php
    header('WWW-Authenticate: Negotiate');
    header('WWW-Authenticate: NTLM', false);
?>
Related