How to use cookies in PHP 7


A cookie is used to identify a user. Cookies are text files stored on the client computer and they are kept of use tracking purpose.

PHP transparently supports HTTP cookies. Browser stores this information on local machine for future use. Server script sends a set of cookies to the browser. For example name, age, or id etc.

A cookie is created with the setcookie() function. Using PHP, you can both create and retrieve cookie values.


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


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

Setrawcookie() is to send a cookie without url encoding the cookie value (for PHP 5, PHP 7)

Only the name parameter is required. All other parameters are optional.

Example Scripts

Create Cookies:

$cookie_value = 'Test_cookie';

setcookie("TestCookie", $value); /* TestCookie is Cookie Name */
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "", 1);

Retrieve Cookies:

// Print an individual cookie
echo $_COOKIE["TestCookie"];

// Another way to debug/test is to view all cookies

Edit Cookies:

if(!isset($_COOKIE[$cookie_name])) {
    echo $cookie_name . "' is not set!";
} else {
    echo $cookie_name . "' is set!<br>";

   /*Again Set Cookie value to updated (New) value */

   setcookie($cookie_name, 'changed value ', time() + (86400 * 30), "/");
    echo "Value is: " . $_COOKIE[$cookie_name];

Delete Cookies:

When deleting a cookie you should assure that the expiration date is in the past.

// set the expiration date to one hour ago
setcookie("TestCookie", "", time() - 3600);
setcookie("TestCookie", "", time() - 3600, "/~rasmus/", "", 1);