A cookie is a small text file with the maximum size of 4KB. Cookie is a medium through which server stores data in the remote browser for the purpose of tracking and identifying return users. So, whenever same computer requests a page with a browser, it will send the cookie too.
The web works based on the HTTP protocol. The HTTP protocol is stateless. When the web browser requests a page from a web server, the web server responds with the page content. Later, the same web browser requests the same page again, the web server has no information that the request is from the same web browser. Cookies solve this stateless challenge. By using Cookie mechanism, server can easily recognise the returning users.
You can set cookie in PHP by using setcookie() function. Below is the syntax:
setcookie(name, value, expire, path, domain, secure);
<?php
// cookie expires in 1 minute
setcookie("Name", "W3TechPoint", time() + 60);
// cookie expires in 1 hour
setcookie("Name", "W3TechPoint", time() + 60 * 60);
// cookie expires in 24 hour
setcookie("Name", "W3TechPoint", time() + 24 * 60 * 60);
Before you access any cookie, you must check whether it is set or not. You can verify is as follows:
<?php
// cookie expires in 1 minute
setcookie("MyName", "W3TechPoint", time() + 60);
if (isset($_COOKIE["MyName"])) {
echo "My name is: " . $_COOKIE["MyName"];
} else {
echo "Cookie is not available!";
}
You can access cookie value by using $_COOKIE superglobal variable. $_COOKIE is an associative array that holds all the cookies values. All the cookies are stored inside this array as list and cookie name is used as key. So, to access any particular cookie you can pass it's key to $_COOKIE array as follows:
<?php
// cookie expires in 1 hour
setcookie("MyName", "W3TechPoint", time() + 60 * 60);
echo "My name is: " . $_COOKIE["MyName"];
To modify a cookie, you just need to set (again) the cookie using the setcookie() function as follows:
<?php
// cookie expires in 1 hour
setcookie("MyName", "New Name", time() + 60 * 60);
You can use setcookie() function to delete a cookie. To delete a cookie, use the setcookie() function with an expiration date in the past as follows:
<?php
// set the expiration time to one hour ago
setcookie("MyName", "W3TechPoint", time() - 3600);
You can verify this as follows:
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
A PHP class that has minimum one abstract method is called as abstract class and cannot be instantiated by itself.
Traits in PHP, are a medium of implementing code reuse and allow us to reuse sets of functions freely in several independent classes.
In this post you will be gaining valuable insights about the PHP sessions and it's working functionalities.