1. Home
  2. Docs
  3. Web Technology II
  4. Cookies, Sessions and Aut...
  5. Setting Cookies in PHP

Setting Cookies in PHP

PHP setcookie() function is used to set cookie with HTTP response.

Syntax:

setcookie(name, value, expire, path, domain, secure, httponly);

  • name: The name of the cookie.
  • value: The value of the cookie.
  • expire: The expiration time as a Unix timestamp. If set to 0, the cookie will expire at the end of the session.
  • path: The path on the server in which the cookie will be available. Default is the current directory.
  • domain: The domain that the cookie is available to. Default is the domain of the current script.
  • secure: Indicates if the cookie should only be transmitted over secure HTTPS connections. Default is false.
  • httponly: When set to true, the cookie will be accessible only through the HTTP protocol and not via JavaScript. Default is false.

Example:

// Setting a cookie with a 30-day expiration
setcookie("user", "John Doe", time() + (86400 * 30), "/");

// Setting a cookie with HTTP Only flag
setcookie("session_id", "123456", time() + 3600, "/", "", true, true);

How can we help?

Leave a Reply

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