What is a cookie in PHP?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too.With PHP, you can both create and retrieve cookie values.
A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the user’s computer. They are typically used to keeping track of information such as username that the site can retrieve to personalize the page when user visit the website next time.
Setting a Cookie in PHP
The setcookie() function is used to set a cookie in PHP. Make sure you call the setcookie() function before any output generated by your script otherwise cookie will not set. The basic syntax of this function can be given with:
setcookie(name, value, expire, path, domain, secure);
name = The name of the cookie.
Value = The value of the cookie. Do not store sensitive information since this value is stored on the user’s computer.
expire =The expiry date in UNIX timestamp format. After this time cookie will become inaccessible. The default value is 0.
path = Specify the path on the server for which the cookie will be available. If set to /, the cookie will be available within the entire domain.
domain = Specify the domain for which the cookie is available to e.g www.login.com.
Secure = This field, if present, indicates that the cookie should be sent only if a secure HTTPS connection exists.
// Setting a cookie
setcookie(“username”, “Priya”, time()+30*24*60*60);
Accessing Cookies Values
The PHP $_COOKIE superglobal variable is used to retrieve a cookie value.
// Accessing an individual cookie value
Advantages of cookies
1)Cookies enable you to store the session information on the client side.
2)Persistence: One of the most powerful aspects of cookies is their persistence. When a cookie is set on the client’s browser, it can persist for days, months or even years. This makes it easy to save user preferences and visit information and to keep this information available every time the user returns to your site. Moreover, as cookies are stored on the client’s hard disk so if the server crashes they are still available.
3)Transparent: Cookies work transparently without the user being aware that information needs to be stored.
They lighten the load on the server’s memory.