×
☰ See All Chapters

PHP Cookies

A cookie is a small piece of information which contains name and value both of type String. Cookies are stored at client side. We can use cookies to store client specific data but it is not a good approach because browser might not support cookies or client may delete cookie. Also storing values in cookie is not secure.

Cookie working mechanism

Cookie object will be created in server and will be moved to the client machine with response object and stored at the client machine. When browser sends the request to application all the cookies related to the application will be attached to request and will go to the server. Always cookie shuttles between client and server.

php-cookies-0
 

 

Types of Cookies

Two types of cookies presents in PHP:

1. Non-persistent/session cookie: Browser removes each time when user closes the browser.

2. Persistent cookie: Browser removes only if user logout or sign-out.

We can specify the expiry time of the cookie. This set time is in seconds and the cookie will stay alive for this period even after the browser shuts down.

Create Cookies in PHP

A cookie is created with the setcookie() function.

Syntax

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

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

Retrieve a Cookie

$_COOKIE array stores all the cookies with cookie name as the key. Below is the syntax to get the cookie value.

Syntax: $_COOKIE["cookiename"];

Modify a Cookie

To modify a cookie, just set (again) the cookie using the setcookie() function. It overrides the previous cookie value.

PHP Cookie Example

<?php

$cookie_name = "user";

$cookie_value = "Manu Manjunatha";

setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

?>

<html>

<body>

 

<?php

if(!isset($_COOKIE[$cookie_name])) {

  echo "Cookie named '" . $cookie_name . "' is not set!";

} else {

  echo "Cookie '" . $cookie_name . "' is set!<br>";

  echo "Value is: " . $_COOKIE["user"];

}

?>

 

</body>

</html>

 


All Chapters
Author