How to Set Cookie in PHP
In this tutorial, we will see how to set a cookie, how to retrieve a cookie, how to update a cookie, and how to delete a cookie in PHP.
Set and retrieve a cookie in php
To set a cookie in PHP use the code below:
<?php
$name = "current_user";
$value = "John Doe";
setcookie($name, $value, time() + (3600 * 10), "/");// 3600 * 10 = 10 hours
?>
<html>
<body>
<?php
if(isset($_COOKIE[$name])) {
echo "Name: " . $name . "<br>";
echo "Value: " . $_COOKIE[$name];
}else{
echo "Cookie not set yet";
}
?>
</body>
</html>
Update a cookie in php
To update a cookie in PHP we use the same code just change the value:
<?php
$name = "current_user";
$value = "Jack Jock";
setcookie($name, $value, time() + (3600 * 10), "/");// 3600 * 10 = 10 hours
?>
<html>
<body>
<?php
if(isset($_COOKIE[$name])) {
echo "Name: " . $name . "<br>";
echo "Value: " . $_COOKIE[$name];
}else{
echo "Cookie not set yet";
}
?>
</body>
</html>
Delete a cookie in php
To delete a cookie we set the expiration date to one hour ago:
<?php
setcookie("current_user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie is deleted.";
?>
</body>
</html>