A cookie in PHP is a small file that is stored on the client computer by the web server, with a maximum size of 4KB. Cookies are typically used to keep track of information such as a username that the site can retrieve to personalize the page when the user visits the website next time. Cookies can only be read from the domain that they have been issued from.
To create a cookie in PHP, the setcookie()
function is used. The function requires at least the name parameter, and all other parameters are optional. The syntax for the setcookie()
function is as follows:
setcookie(name, value, expire, path, domain, secure, httponly);
The name
parameter is the only required parameter, and it sets the name of the cookie. The value
parameter sets the value of the cookie. The expire
parameter sets the expiration time of the cookie. The path
parameter sets the path on the server for which the cookie will be available. The domain
parameter sets the domain for which the cookie is available. The secure
parameter indicates that the cookie should be sent only if a secure HTTPS connection exists. The httponly
parameter indicates that the cookie should only be accessible through the HTTP protocol.
To retrieve the value of a cookie, the global variable $_COOKIE
is used. The isset()
function can be used to check if the cookie is set.
Here is an example of creating and retrieving a cookie named "user" with the value "John Doe" that will expire after 30 days (86400 * 30) :
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named " . $cookie_name . " is not set!";
} else {
echo "Cookie " . $cookie_name . " is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
Note that the setcookie()
function must appear before the <html>
tag.