Sameera Abeysekara
2 min readOct 23, 2020

PHP Cookies

A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the user’s computer. They are typically used to keeping track of information such as username that the site can retrieve to personalize the page when user visit the website next time.

Setting a Cookie in PHP

The setcookie() function is used to set a cookie in PHP. Make sure you call the setcookie() function before any output generated by your script otherwise cookie will not set

setcookie(name, value, expire, path, domain, secure);

The parameters of the setcookie() function have the following meanings:

Tip: If the expiration time of the cookie is set to 0, or omitted, the cookie will expire at the end of the session i.e. when the browser closes.

Here’s an example that uses setcookie() function to create a cookie named username and assign the value value John Carter to it. It also specify that the cookie will expire after 30 days (30 days * 24 hours * 60 min * 60 sec).

setcookie("username", "John Carter", time()+30*24*60*60);

Accessing Cookies Values

The PHP $_COOKIE superglobal variable is used to retrieve a cookie value. It typically an associative array that contains a list of all the cookies values sent by the browser in the current request, keyed by cookie name. The individual cookie value can be accessed using standard array notation, for example to display the username cookie set in the previous example, you could use the following code.

// Accessing an individual cookie value
echo $_COOKIE["username"];

Removing Cookies

You can delete a cookie by calling the same setcookie() function with the cookie name and any value (such as an empty string) however this time you need the set the expiration date in the past, as shown in the example below:

// Deleting a cookie
setcookie("username", "", time()-3600);

iis cors access-control-allow-origin