How To Set Cookie In PHP?

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:

  1. The name of the cookie
  2. The value of the cookie
  3. The expiration time of the cookie (in seconds since the Unix Epoch)
  4. The path on the server where the cookie will be available
  5. The domain that the cookie is available to
  6. Whether the cookie should only be transmitted over a secure HTTPS connection
  7. 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 ""
setcookie("subdomain_cookie", "subdomain_value", time()+3600, "/", "");

// Set a secure cookie that is accessible only through HTTPS
setcookie("secure_cookie", "secure_value", time()+3600, "/", "", true, true);

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories