What is Cookie?
A cookie is a small text file that a website stores on a user’s computer or mobile device when the user visits the website. Cookies contain information about the user and their browsing activity, and they are used by websites to provide a personalized browsing experience and to track user behavior for analytical and marketing purposes.
How to Set Cookie:
To set a cookie in PHP, you can use the setcookie()
function. The setcookie()
function takes up to seven parameters:
- The name of the cookie
- The value of the cookie
- The expiration time of the cookie (in seconds since the Unix Epoch)
- The path on the server where the cookie will be available
- The domain that the cookie is available to
- Whether the cookie should only be transmitted over a secure HTTPS connection
- Whether the cookie should be accessible only through HTTP (not JavaScript)
Here is an example of how to set a cookie in PHP:
// Set a cookie with the name "my_cookie" and the value "Hello, world!" setcookie("my_cookie", "Hello, world!"); // Set a cookie that expires in 1 hour (3600 seconds) and is available only on the /admin path setcookie("admin_cookie", "secret_value", time()+3600, "/admin"); // Set a cookie that is available only on the subdomain "example.com" setcookie("subdomain_cookie", "subdomain_value", time()+3600, "/", "example.com"); // Set a secure cookie that is accessible only through HTTPS setcookie("secure_cookie", "secure_value", time()+3600, "/", "", true, true);