In PHP, a cookie is a small piece of data that is sent by a website to a user’s web browser and stored on the user’s computer. Cookies are used to remember user preferences, login credentials, or other information across multiple requests.
To create a cookie in PHP, you can use the
setcookie() function. This function takes up to six parameters:
- Name: The name of the cookie.
- Value: The value of the cookie.
- Expiration time: The time at which the cookie will expire, expressed as a Unix timestamp.
- Path: The path on the server where the cookie will be available.
- Domain: The domain name where the cookie will be available.
- Secure: A boolean flag indicating whether the cookie should be sent only over secure HTTPS connections.
For example, to create a cookie named
username with a value of
john_doe that expires in one hour, you can use the following code:
setcookie('username', 'john_doe', time() + 3600);
To retrieve the value of a cookie in PHP, you can use the
$_COOKIE superglobal array. For example:
$username = $_COOKIE['username'];
Note that cookies are stored on the user’s computer and can be modified or deleted by the user. Therefore, you should never store sensitive information such as passwords in cookies. Additionally, some users may disable cookies in their web browser, so your application should be able to function without relying on cookies.