Cookie In PHP

Cookie Scenario : A user requests a secure search in the browser, and for that, the search function checks whether the user is has logged in or not. If yes, it proceeds else it will ask the user to login by displaying a login form.

In this scenario, the search function searches for a text file in browser which stores the user credentials. If valid/existing data is found then it redirects further.

This encrypted text file is named as Cookie which is stored on a user's computer in browser's directories. They are designed to hold a modest amount of data specific to a particular client and website.

Why to use cookie?

HTTP is a stateless protocol , so to pass the information across web pages Cookies are used. It stores state information .
1. The browser can store information in a Cookie file after the user login, so that the system can remember the state information.
2. Cookie is a message given to a web browser. The browser stores the message in a text file.
3. The message is then sent back to the server each time the browser requests a page from the server.

Setting cookie

setcookie function must be placed before any HTML tag. time() returns the present system time. The cookie will expire after 3600 seconds of creation, i.e. 1 hour after creation. To destroy a cookie set a negative time

#Syntax
setcookie (name, value, expires);
#Example
setcookie("Name", "Prateek", time()+3600);

Retrieving cookie

$_COOKIE variable can be used to retrieve the values of the existing cookies.

#Syntax
$_COOKIE['name']
#Example
echo 'Welcome '.$_COOKIE['EName'];