Cookies are text files that allow programmers to store certain information on the client's computer for tracking purposes so that the information can be retrieved and used later in the program as needed.
Create a Cookie
PHP offers various functions according to the purposes, and one of them is setcookie()
which is used to set a cookie on the client machine.
Syntax:
setcookie(name, value, expiration);
- $name - a name of the cookie. Example: "username"
- $value - a value of the cookie. Example: "Jhon"
- $expire - time (in UNIX timestamp) when the cookie will expire. Example: time()+"3600". A cookie is set to expire after one hour.
Example:
<?php setcookie("username", "Alex", time()+3600); ?>
In the above example, a cookie as a "username" is set on the user's computer with a value that will expire automatically after an hour.
Retrieve a Cookie Value
PHP $_COOKIE is an automatic global or 'superglobal' variable that retrieves the cookie value.
Example:
<?php echo $_COOKIE["username"]; ?>
You can use the PHP isset()
function to determine whether the cookie is already set.
Example:
<?php
if (isset($_COOKIE["username"]))
echo "Welcome " . $_COOKIE["username"] . "!<br>";
else
echo "Welcome guest!<br>";
?>
If you want to see the full $_COOKIE
array, you can do the following.
Example:
<pre>
<?php print_r($_COOKIE); ?>
</pre>
Delete a Cookie
To delete a cookie, you just need to set that cookie to a previous date. The following PHP code will delete the cookie we set in the above example.
Example:
<?php setcookie("username", "", time()-3600); ?>
or
<?php setcookie('username', null, -1, '/'); ?>