How do you use cookies in PHP?

The method of using cookies in PHP is to set the value of the cookie using the setcookie() function.

The syntax for the setcookie() function is as follows:

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

Description of parameters:

  1. name: the name of the cookie.
  2. value: the value of the cookie.
  3. Expiration: The expiration time of a cookie can be a timestamp (in seconds) or a specific date and time string. If this parameter is not set, the cookie will automatically expire once the browser is closed.
  4. The default path for cookies is the current path.
  5. Default is an empty domain field for cookies, which means they are valid for the current domain.
  6. Is it only when using a secure HTTPS connection that cookies are sent?
  7. HttpOnly: restricts the cookie to be accessible only through the HTTP protocol, preventing access through JavaScript.

Here is an example of setting a cookie:

setcookie("username", "John Doe", time()+3600, "/", ".example.com", true, true);

The example above creates a cookie named “username” with the value “John Doe” that expires in one hour. The cookie is valid for the entire website’s path, can only be accessed through a secure HTTPS connection, and is restricted from being accessed through JavaScript.

To retrieve the value of a cookie, you can use the $_COOKIE superglobal variable, as shown below:

$username = $_COOKIE["username"];

The above code sets the value of the cookie named “username” from $_COOKIE to the variable $username.

To delete a cookie, you can immediately expire it by setting the expiration time to a past time, as shown below:

setcookie("username", "", time()-3600);

The above code immediately sets the cookie named “username” to expire, thus deleting the cookie.

bannerAds