codecowboy
codecowboy

Reputation: 31

How to set multiple cookies by using php header

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)

Upvotes: 3

Views: 2567

Answers (2)

Gökhan Ege
Gökhan Ege

Reputation: 55

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

Upvotes: 2

Alan Stewart
Alan Stewart

Reputation: 93

Putting an actual answer here instead of hidden in the comments.

As rugolinifr said, "set the second argument to false", as per https://www.php.net/manual/fr/function.header.php

Upvotes: 1

Related Questions