PHP Cookies

Cookies are pieces of content that are sent to a user's web browser. Cookies can enable you to make shopping carts, client groups, and customized destinations. It's not prescribed that you store sensitive data in a cookie, but you can store a unique identification string that will coordinate a user with information held safely in a database.

Create Cookies in PHP

To set a cookie, we need to call the setcookie() function before sending any other content to the browser because a cookie is actually part of the header information.

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

Here, only the name parameter is required. All other parameters are optional.

Parameter Description
name It holds the name of the variable that is kept in the global $_COOKIE and is available in resulting scripts.
value The value of the variable is passed in the name parameter. This can contain up to 4 KB of alphanumeric text.
expire It is an optional parameter. It sets a particular Unix timestamp of the expiration date. Generally, you will probably use time() plus a number of seconds. If time is not set, the cookie expires when the web browser closes.
path It is an optional parameter. It is the path of the cookie on the server. If a single slash is in the path parameter, the cookie is valid for all files and directories on the web server. If a specific directory is named, this cookie is valid only for pages within that directory.
domain It is an optional parameter. Cookies are valid only for the host and domain that set them. If no domain is specified, the default value is the host name of the server that generated the cookie.
secure It is an optional parameter. If the security parameter is TRUE, the cookie will only be transmitted via HTTPS, which is to say, over a secure web server. The default is FALSE.
httponly It is an optional parameter and implemented since PHP version 5.2.0. Whether the cookie must use the HTTP protocol or not. The default is FALSE.

Example of PHP Cookies

   setcookie("name", "Smith", time()+3600, "/","", 0);
   setcookie("department", "IT", time()+3600, "/", "",  0);

The above example creates two cookies named "name" and "department" with the values "Smith" and "IT". Both cookies will be expired after one hour.

Accessing Cookies Values

Here, you will learn how to retrieve the cookie values that you've previously set. There are many ways to access cookies in PHP. The easiest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables.

if (isset($_COOKIE['name'])) {
    echo "Name is ".$_COOKIE['name'];
if (isset($_COOKIE['department'])) {
    echo "Department is ".$_COOKIE['department']";

Deleting Cookies

To delete the setcookie values, you should call the setcookie( ) with no name argument for the cookie and set the expiration time in the past.

Example -

   setcookie("name", "", time()-3600);
   setcookie("department", "", time()-3600);

Read more articles

General Knowledge

Learn Popular Language