Cookies

suggest change

Introduction

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.

Syntax

PHP 7.3 and later also accept an $options array as the third argument.

Parameters

Parameter Detail
name The name of the cookie. This is also the key you can use to retrieve the value from the $_COOKIE superglobal. This is the only required parameter
value The value to store in the cookie. This data is accessible to the browser, so don’t store anything sensitive here.
expire A Unix timestamp representing when the cookie should expire. If set to zero, the cookie expires at the end of the session. If set to a number less than the current Unix timestamp, the cookie expires immediately.
path The scope of the cookie. If set to /, the cookie is available within the entire domain. If set to /some-path/, the cookie is available only in that path and its descendants. The default is the current directory of the script that sets the cookie.
domain The domain or subdomain the cookie is available on. If set to the bare domain stackoverflow.com, the cookie is available to that domain and all subdomains. If set to a subdomain meta.stackoverflow.com, the cookie is available only on that subdomain and its subdomains.
secure When true, the Set-Cookie header includes the Secure attribute. The browser then sends the cookie only over HTTPS. PHP still sends the header on an HTTP response.
httponly When true, the cookie is available through HTTP and is not exposed to client-side scripting languages such as JavaScript. Available since PHP 5.2.

Remarks

Calling setcookie does not put the given data into the $_COOKIE superglobal.

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents