last edited on: 19-Jan-2018; tagged: php,cookies
What is a Cookie?
A cookie is a small text file that we can store on user’s computer to store a small amount of data on the user's computer through the browser.
What is a cookie in PHP?
PHP supports HTTP cookie. Server script sends a set of cookies to the user’s browser. Browser stores this information on local machine based on website/domain, cookies name, expire date, values/information etc for future use. Later web server can retrieve those cookies.
PHP provided setcookie() function to set a cookie. Cookies are part of the HTTP header, so setcookie() function must be called before any output is sent to the browser. setcookie() function requires six arguments. For each cookie (that we want to set) this function has to be called separately.
setcookie() Function Syntax
bool setcookie(name, value, expire, path, domain, security);
** Here only the name parameter is required. All other parameters are optional.
** The setcookie() function must appear BEFORE the <html> tag.
Setting a Cookie in PHP
In the above example the setcookie() function creates a cookie named username and assign the value value " Samantha Smith to it. It also specify that the cookie will expire after 1 days (1 days * 24 hours * 60 min * 60 sec).
Accessing Cookies Values in PHP
PHP provides many ways to access cookies. Simplest way is to use $_COOKIE superglobal variable to retrieve a cookie value. Here is also $HTTP_COOKIE_VARS variable to access cookie. But $HTTP_COOKIE_VARS variable is deprecated. Following example will access the cookie set in above example.
The PHP code in the above example produce the following output:
It is always a good practice to check whether a cookie is set or not before accessing its value. We can use the PHP isset() function, like this:
We can use the print_r() function as print_r($_COOKIE); to see the structure of this $_COOKIE associative array.
Removing/Deleting Cookies in PHP
We can delete a cookie by calling the same setcookie() function with the cookie name by setting the expire date in past as below:
We must pass exactly the same path, domain, and other arguments that we have used to create the cookie in order to ensure that the correct cookie is deleted.