Professional Documents
Culture Documents
PHP Cookies: What Is A Cookie
PHP Cookies: What Is A Cookie
Cookies
In this tutorial you will learn how to store a small amount of information within
the user's browser itself using the PHP cookies.
What is a Cookie
A cookie is a small text file that lets you store a small amount of data (nearly
4KB) on the user's computer. They are typically used to keeping track of
information such as username that the site can retrieve to personalize the
page when user visit the website next time.
Tip: Each time the browser requests a page to the server, all the data in the
cookie is automatically sent to the server within the request.
Parameter Description
name The name of the cookie.
value The value of the cookie. Do not store sensitive information since this value is stored on the user's co
expires The expiry date in UNIX timestamp format. After this time cookie will become inaccessible. The de
value is 0.
path Specify the path on the server for which the cookie will be available. If set to /, the cookie will be a
within the entire domain.
domain Specify the domain for which the cookie is available to e.g www.example.com.
secure This field, if present, indicates that the cookie should be sent only if a secure HTTPS connection ex
Tip: If the expiration time of the cookie is set to 0, or omitted, the cookie will
expire at the end of the session i.e. when the browser closes.
Example
Download
<?php
// Setting a cookie
setcookie("username", "John Carter", time()+30*24*60*60);
?>
Note: All the arguments except the name are optional. You may also replace
an argument with an empty string ("") in order to skip that argument, however
to skip the expire argument use a zero (0) instead, since it is an integer.
Example
Download
<?php
// Accessing an individual cookie value
echo $_COOKIE["username"];
?>
The PHP code in the above example produce the following output.
John Carter
It's a good practice to check whether a cookie is set or not before accessing its
value. To do this you can use the PHP isset() function, like this:
Example
Download
<?php
// Verifying whether a cookie is set or not
if(isset($_COOKIE["username"])){
echo "Hi " . $_COOKIE["username"];
} else{
echo "Welcome Guest!";
}
?>
Example
Download
<?php
// Deleting a cookie
setcookie("username", "", time()-3600);
?>
Tip: You should pass exactly the same path, domain, and other arguments
that you have used when you first created the cookie in order to ensure that
the correct cookie is deleted.