elibraryportal Logo

Cookies in PHP

⟼ Cookie is a small piece of information which is identify a user that stored information client browser

⟼ A cookie is maximum size of 4KB small file where Cookie is created at server side and saved to client browser. every time client sends request to the server, cookie is embedded with request.

Fig:-

Cookies in PHP

Where

1) A user requests for a page that stores cookies

2) The server sets the cookie on the user's computer

3) Other page requests from the user will return the cookie name and value


Create Cookies in PHP

1) setcookie() function in PHP

setcookie() function is used to set cookie with HTTP response.

setcookie() returns boolean.

setcookie() function must appear BEFORE the <html> tag.

Syntax:-

where All other parameters are optional in setcookie

PHP $_COOKIE

Superglobal variable are used to get cookie $_COOKIE.

Example

PHP Cookie Full Example

File: cookie1.php

Output:

Sorry, cookie is not found!

But, When you refresh the page, you will see cookie is set now.

Output:

Cookie Value: elibraryportal

PHP Delete Cookie

setcookie() function is ues the expiration date in past, cookie will be deleted.

File: cookie2.php

Output:

Cookie 'user' is deleted.

Next Topic