PHP 7 Cookies

Cookies are pieces of content that are sent to a user's web browser. Cookies can enable you to make shopping cart, 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 must 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);

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 passed in the name parameter. This can contain up to 4 KB of alphanumeric text.
expire It is 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 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 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 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 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

<?php 
   setcookie("name", "Smith", time()+3600, "/","", 0);
   setcookie("department", "IT", time()+3600, "/", "",  0);
?>

Accessing Cookies Values

Here, we will learn to retrieve the cookie values that you've previously set. $_COOKIE superglobal variable is used to get the previously set cookie values.

<?php 
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, call setcookie( ) with no value for the cookie and set the expiration time in the past.

Example -

<?php 
   setcookie("name", "", time()-3600);
   setcookie("department", "", time()-3600);
?>





Read more articles


General Knowledge



Learn Popular Language