In PHP, cookies are used to store small pieces of data on the user's browser. These data can be retrieved later and used for various purposes like tracking user preferences, sessions, or remembering login information.
What are Cookies?
Cookies are small files that are stored on the user's device by the web browser.
Cookies can store key-value pairs of data and have attributes like expiration time, domain, path, and security options.
Cookies are sent with every HTTP request to the server until they expire.
Create Cookies With PHP
To set a cookie in PHP, you use the setcookie() function. Here's the basic syntax:
echo"Cookie named '" . $cookie_name . "' is not set!";
} else {
echo"Cookie '" . $cookie_name . "' is set!<br>";
echo"Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
To delete a cookie, you need to set its expiration time to a past date. This will tell the browser to delete the cookie.
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo"Cookie 'user' is deleted.";
?>
</body>
</html>
Check if Cookies are Enabled
To check if cookies are enabled in the user's browser using PHP, you can use a simple technique that involves setting a test cookie and then checking if it was successfully set.
If the cookie is set correctly, it means cookies are enabled.
We use cookies and similar technologies to enhance your browsing experience, serve personalized content and advertisements, and analyze our traffic.
By clicking "Accept All", you consent to our use of cookies and the processing of your personal data for these purposes.
You can manage your preferences or learn more in our
Privacy Policy and
Cookie Policy.