Cookie: A Cookie is a small file sent by the server to preserve stateful information for a user. It is stored on the client’s computer and sent to the server every time the user makes a request for the same page.
To create cookies you can set the cookie by using the setcookie() function of the PHP.
setcookie(name, value, expire, path, domain, secure, httponly)
Parameters: This function accepts seven parameters as mentioned above and described below:
- name: The name of the cookie.
- value: The value you want to store in the cookie.
- expire-time: It is the number of seconds until the cookie will be kept on the user’s machine by the browser. After that, it will automatically be deleted. If not set then the cookie will be preserved by browser until it is open.
- path: It determines for which directories cookie will valid. If you want to access it in all directories then put it on “/”, i.e. the cookie is accessible in the entire domain. Otherwise, the cookie will be limited to the subdirectory.
- domain: It is used to define the access hierarchy for the cookie. For example, if you set this to “yourdomain.com”, it will be accessible via all the subdomains also. but if it set to “sub.yourdomain.com”, it will be accessible by “sub.yourdomain.com” and its subdomains.
- secure: It determines how the cookie will be sent, via HTTP or HTTPS. If set to true then the cookie will be sent via HTTPS only, otherwise, it will be sent via HTTP. Its default value is false.
Out of the above parameters, only the first two parameters are mandatory. Others are optional parameters. If you want to preserve the cookie, then provide the expire-time parameter.
Note: It is stored in the global array named $_COOKIE.
Creating a Cookie: As mentioned earlier, we can set cookies by using the function setcookie().
Cookie 'gfg' is set! Value is: GeeksforGeeks
Deleting Cookie: There is no special dedicated function provided in PHP to delete a cookie. All we have to do is to update the expire-time value of the cookie by setting it to a past time using the setcookie() function. A very simple way of doing this is to deduct a few seconds from the current time.
setcookie(name, time() - 3600);
Cookie 'gfg' is deleted.
Note: The setcookie() function must appear before the <html> tag.