904 Contributors: 17 Thursday, June 29, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial:
Roadmap: roadmap



An HTTP cookie is a small piece of data sent from a website and stored on the user's computer by the user's web browser while the user is browsing.


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


nameThe name of the cookie. This is also the key you can use to retrieve the value from the $_COOKIE super global. This is the only required parameter
valueThe value to store in the cookie. This data is accessible to the browser so don't store anything sensitive here.
expireA Unix timestamp representing when the cookie should expire. If set to zero the cookie will expire at the end of the session. If set to a number less than the current Unix timestamp the cookie will expire immediately.
pathThe scope of the cookie. If set to / the cookie will be available within the entire domain. If set to /some-path/ then the cookie will only be available in that path and descendants of that path. Defaults to the current path of the file that the cookie is being set in.
domainThe domain or subdomain the cookie is available on. If set to the bare domain then the cookie will be available to that domain and all subdomains. If set to a subdomain then the cookie will be available only on that subdomain, and all sub-subdomains.
secureWhen set to TRUE the cookie will only be set if a secure HTTPS connection exists between the client and the server.
httponlySpecifies that the cookie should only be made available through the HTTP/S protocol and should not be available to client side scripting languages like JavaScript. Only available in PHP 5.2 or later.


It is worth noting that mere invoking setcookie function doesn't just put given data into $_COOKIE superglobal array.

For example there is no point in doing:

setcookie("user", "Tom", time() + 86400, "/");
var_dump(isset($_COOKIE['user'])); // yields false or the previously set value

The value is not there yet, not until next page load. The function setcookie just says "with next http connection tell the client (browser) to set this cookie". Then when the headers are sent to the browser, they contain this cookie header. The browser then checks if the cookie hasn't expired yet, and if not, then in http request it sends the cookie to the server and that's when PHP receives it and puts the contents into $_COOKIE array.

Related Examples