Cookies in PHP allow storing pieces of data on the client's browser .
Cookie store on you local browser
How cookies work in PHP:
1. Set Cookie:
To set a cookie in PHP, you use the setcookie() function.
This function takes parameters such as the name of the cookie, its value, expiration time, and other optional settings.
<?php
// Set a cookie named "username" with value "john123"
setcookie("name", "tutorials On Web", time() + 3600, "/");
?>
In this example, the cookie named "username" is set with the value "tutorials On Web
". The cookie will expire in 1 hour (time() + 3600), and its path is set to the root directory ("/").
2. Retrieve Cookie:
Once a cookie is set, PHP can retrieve its value using the $_COOKIE super global array.
<?php
$name = $_COOKIE['username'];
?>
This code retrieves the value of the "username" cookie and assigns it to the $username variable.
3. Modify Cookie:
You can modify a cookie by setting it again with new values.
<?php
setcookie("name", "new_value", time() + 3600, "/");
?>
4. Delete Cookie:
To delete a cookie, you set it with an expiration time in the past.
<?php
// Delete the "username" cookie
setcookie("username", "", time() - 3600, "/");
?>