add cookie in php

To set a cookie in PHP, you can use the setcookie() function, which takes at least two parameters: the name of the cookie and its value.

main.php
// set a cookie named "username" with value "John"
setcookie("username", "John");
82 chars
3 lines

By default, a cookie set with setcookie() will expire when the user's browser is closed. However, you can set an expiration date using a third parameter, which takes a Unix timestamp or a string in the format YYYY-MM-DD HH:MM:SS.

main.php
// set a cookie named "username" with value "John" that expires in 30 days
$expiration = time() + (30 * 24 * 60 * 60);
setcookie("username", "John", $expiration);
163 chars
4 lines

You can also set additional parameters such as the cookie's path, domain, and whether it should only be sent over HTTPS. For example, to make the cookie secure, you can pass true as the fourth parameter.

main.php
// set a secure cookie named "username" with value "John"
$expiration = time() + (30 * 24 * 60 * 60);
setcookie("username", "John", $expiration, "/", "example.com", true, true);
178 chars
4 lines

Note that setcookie() must be called before any output is sent to the browser, including whitespace.

gistlibby LogSnag