0

PHP's setcookie function looks like this:

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

As you can see, domain has no standard value, but the following parameters (httponly and secure) do.

I want both last parameters set to true, but without specifying a domain to bind the cookie to. Is that even possible? Sadly, PHP doesn't allow something like this:

setcookie('name', 'value', time()+60, '/', $secure=true, $httponly=true);

Also see this SO question with a similar problem. Obviously, I cannot change the setcookie function.

EDIT

Setting the domain parameter to "" or null does not work.

Community
  • 1
  • 1
paolo
  • 2,528
  • 3
  • 17
  • 25
  • According to the docs, the default for `$domain` is an empty string, so this should work: `setcookie('name', 'value', time()+60, '/', '',true, true);` – Steve May 27 '16 at 14:47
  • I just tried, it doesn't work. Btw, I'm on a local domain for development, `.localhost`, maybe that's the issue? – paolo May 27 '16 at 14:56
  • Have you tried setting the domain parameter as null? – Azae B. Garcia May 27 '16 at 15:06
  • Doesnt't work either. – paolo May 27 '16 at 15:10
  • I just tried it with `null` value and it worked on PHP 5.6. The domain is not set in Set-Cookie header and browser (Chrome) sets it then to the current domain. – krzychu Jan 23 '17 at 14:51

1 Answers1

1

Testing this on my own development server (PHP 7.3.4), submitting an empty string for the domain works. Submitting null may work as well, but with declare(strict_types=1) set, PHP generates a message about an incorrect parameter type, string required, NULL supplied.

For example:

setcookie('myCookie', 'myCookieData', 0, '/, '', true, true);

but not

setcookie('myCookie', 'myCookieData', 0, '/, null, true, true);

However, setcookie() allows cookie options to be supplied as an array.

For example:

setcookie('myCookie', 'myCookieData',['expires'=>0, 'path'=>'/', 'domain'=>'example.com', 'httponly'=>true, 'secure'=>true];

This allows the domain to be omitted from the array, and it's thus not sent to the client:

setcookie('myCookie', 'myCookieData',['expires'=>0, 'path'=>'/', 'httponly'=>true, 'secure'=>true];

PHP setcookie() page