What are Cookies in PHP?

Cookies in PHP are small files stored on the user’s browser to remember information between different page requests. They are typically used for:

  • User login sessions
  • Remembering user preferences
  • Tracking user activity

 

How Cookies Work:

  1. The server sends a cookie using PHP.

  2. The browser stores it.

  3. On every subsequent request, the browser sends the cookie back to the server.

How to Set a Cookie in PHP:

login.php


// Set a cookie
setcookie("user", "John", time() + 3600); // valid for 1 hour
  • user = Cookie name
  • "John" = Cookie value
  • time() + 3600 = Expiration time (current time + 1 hour)

 

How to Retrieve a Cookie:


echo $_COOKIE['user']; // Outputs: John

How to Delete a Cookie:


setcookie("user", "", time() - 3600); // Set expiration time to the past

Note:

  • Cookies are stored in the user’s browser.
  • Size limit: ~4KB
  • They are sent with every HTTP request—use them wisely to avoid performance issues.