Cookies are the small text file that is stored on the client local computer. When client computer requests a page with a browser, then it sends the cookies data to the web server that is reduce the server response time. In PHP, you can create, retrieve and delete cookie values both.
Here, there are 3 steps to identify users by cookies:
- Server sends a set of cookies to the client local browser like user name, city, pin code etc.
- Client browser stores cookies data on local system when web server sends first time cookies data.
- In future, when browser sends any request to the server then it sends all cookies data to the server and server uses that data to identify the unique user.
How to set cookies with PHP?
For set cookies, we will use setcookie() function.
setcookie(name, value, expire, path, domain, secure);
Note: On above syntax, only name parameter is required and all other parameters are optional.
Below is detail of all parameter:
- Name: This is a required parameter. It is the name of the cookie and it is stored in an environment variable that is called HTTP_COOKIE_VARS.
- Value: This is the content of name parameter that is actually stores for future use.
- Expiry: This is the time limitation of cookies. If you will not set expiry, it will automatically expire when browser is closed.
- Path: This is a directory for which the cookie is valid. The single forward slash means that the cookie is available in the entire website.
- Domain: All cookies are only valid for the specific domain name.
- Security: This shows, way of cookies either HTTPS or HTTP. If cookie is set to 1 then it will send to HTTPS otherwise it will send by regular HTTP.
Note: The setcookie() function must use BEFORE the starting oftag.
The following example creates a cookie that name is "sr" with the value "srcraft india". The following cookie will expire after 10 days (86400 * 10).
Note: 86400 means one day.
How to modify a Cookie value?
For modify a cookie, There are no another way. We have to set again cookie using the setcookie() function.
How to delete a Cookie?
How to check cookies are enabled or not?
Before checking cookies are enabled or not, we have to set cookies. After that we have to count the $_COOKIE array variable
For more, visit: how to set cookies in php