Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 202
codecowboy Avatar asked Dec 18 '25 10:12

codecowboy


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);
?>
like image 87
Gökhan Ege Avatar answered Dec 21 '25 01:12

Gökhan Ege


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

like image 22
Alan Stewart Avatar answered Dec 21 '25 01:12

Alan Stewart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!