Cookies in PHP


The server stores small data pieces called cookies in the client’s browser. Cookies are used to:

  • Track user activity
  • Remember preferences or settings
  • Keep users logged in
php-cookies

Set a Cookie

Use setcookie() before any output is sent to the browser.

 

<?php
// Set cookie: name, value, expiry time, path
setcookie("username", "Alice", time() + 3600, "/"); // 1 hour
echo "Cookie has been set.";
?> 

Syntax

setcookie(name, value, expire, path, domain, secure, httponly);
 

Retrieve a Cookie

 <?php
if (isset($_COOKIE["username"])) {
    echo "Hello, " . $_COOKIE["username"];
} else {
    echo "Cookie not set.";
}
?>

Delete a Cookie

Set the expiry time in the past:

 

<?php
setcookie("username", "", time() - 3600, "/");  // Expired
echo "Cookie deleted.";
?> 

Cookie Best Code Practices

  • Use the httponly flag to prevent JavaScript access
  • Use the secure flag for HTTPS-only cookies
  • Always validate cookie values before trusting them

Task Function/Code
Set Cookie setcookie("name", "value", time()+3600);
Get Cookie $_COOKIE["name"]
Delete Cookie setcookie("name", "", time()-3600);
Check Existence isset($_COOKIE["name"])



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.