Cookies are small text files that are stored on the client’s computer by the browser. They are used to store data that can be accessed on subsequent visits to the website. In PHP, cookies can be set, read, and deleted using the
$_COOKIE superglobal, and
setcookie() function is used to set a cookie. The function takes at least two arguments: the name of the cookie and its value.
setcookie("username", "John", time() + (86400 * 30), "/");
The above code sets a cookie named “username” with the value “John” that expires in 30 days. The last argument “/” indicates that the cookie is available throughout the entire website.
You can also set other optional parameters like
To read the value of a cookie, you can use the
$_COOKIE superglobal array.
$username = $_COOKIE['username'];
To delete a cookie, you can set its expiration time to a past date using the
setcookie("username", "", time() - 3600);
It is important to note that cookies can only be accessed by the domain that set them, also when working with cookies you should consider the user’s privacy and follow the laws and regulations that apply to your country or region.
Cookies can also be used to store session data, which allows you to keep track of a user’s actions across multiple pages. PHP provides the
session_start() function to start a new session, and the
$_SESSION superglobal array to store and access session data.