How to create Cookie:
To use this function, you can specify six parameters, only name is mandetory others are optional:
- name – specifies the name (rows) assigned to the Cookie;
- value – specifies the value of a variable (string);
- Expire – time of expiration of the variable (integer). If this parameter is not specified, the Cookie will be available before the end of the session, that is, until you close your browser. If time is specified, when it comes, Cookie self-destruct.
- path – the path to Cookie (string);
- domain – a domain (a string). The value is set host name from which the Cookie has been established;
- secure – Cookie transmission over a secure HTTPS-connection.
The cookie expires when the expiration date is automatically deleted.
Let’s create an example to create the cookie.
Here setcookie set the name value with time function which finds the current time and adds 60 * 60 * 24, so the cookie will be available for one day and 24 hours, the cookie will be deleted.
How to retrieve Cookie:
After your cookies have been set successfully in user’s browser,you can read a cookie on the next request from that browser.
To retrieve cookie using the name passed when create a cookie and will retrieve the value.
They are kept in superglobal $_COOKIE and $HTTP_COOKIE_VARS with the cookie name as an index, and the value as the value it indexes.
You can retrieve a cookie as follows:
In this example,The first time a script is set Cookie”cookie_name” with value “cookie_value”. At the next line to the script, will display the value of Cookie “cookie_name”, that is, the string “cookie_value”.$_COOKIE is an associative array is an array of all of the cookies that have been sent to the server is stored.
You can use cookie anywhere in your script in PHP.You can retrieve cookie only after cookie has been set,
How to Update Cookie
To change the assigned value in the cookie,same setcookie function will be updating the old assigned value in the cookie.
You will get the same cookie with different values or can say second value.
How to delete Cookie
Sometimes you want to remove Cookies.Deleting a cookie is easy.To delete cookies,there are two methods to use
- unset function
- setcookie function with previous expire value
Let’s check the unset function
Let’s see the next option to delete the cookie.Here, you can use setcookie(), with the exact same arguments except for the value which should be set to as an empty string or you can set an expiration time in the past to delete the cookie.
DrawBack of cookie in PHP:
- Some very old browsers do not support cookies.
- Sometimes browser refuses to accept cookies and setcookie() function does not even return a value which indicates acceptance or refusal of the cookie