PHP Cookies

Introduction

A cookie is a small piece of data stored in the user’s browser by the server. Cookies allow websites to remember user information across different visits.

PHP provides built-in functions to create, read, and delete cookies. Cookies store data on the client side (browser) rather than on the server.

Cookies are widely used in login systems, tracking user preferences, analytics, and maintaining user sessions.

What is PHP Cookies?

A PHP cookie is used to store the user’s information on the browser.

Cookies are created using the setcookie() function in PHP.

Example:


setcookie("username", "John", time() + 3600);

This cookie stores the value “John” and expires after one hour.

Cookies can be accessed using the $_COOKIE superglobal array.

Example:


echo $_COOKIE["username"];

Why It Is Used

Cookies are used for several purposes in web development.

1. Remember User Login

Websites can remember user login details.

2. Store Preferences

Cookies store user preferences like language or theme.

3. Website Analytics

Cookies help track user behavior on websites.

4. Personalization

Websites can personalize content based on stored cookies.

5. Shopping Cart Data

Cookies may temporarily store product selections.

Syntax

Creating a cookie:


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

Example:


setcookie("user", "John", time() + 3600);

Reading a cookie:


echo $_COOKIE["user"];

Deleting a cookie:


setcookie("user", "", time() - 3600);

Example:


setcookie("user", "John", time() + 3600);
if(isset($_COOKIE["user"])) {
  echo "Welcome " . $_COOKIE["user"];
} else {
  echo "Cookie not set";
}

Explanation:

  1. A cookie is created.
  2. The cookie stores the value.
  3. The cookie is retrieved using $_COOKIE.

Real-Life Example

A common example of cookies is remember me login functionality.

When users check “Remember Me” during login:

  1. The website creates a cookie.
  2. The cookie stores the user ID.
  3. When the user returns, the system automatically logs them in.

Cookies are also used in:

  • Language preference storage
  • Dark/light mode settings
  • Advertising tracking
  • Website analytics

Common Mistakes

1. Not Setting Expiration Time

Cookies without expiration may expire when the browser closes.

2. Sending Output Before setcookie()

Cookies must be set before HTML output.

3. Storing Sensitive Data

Cookies should not store passwords or sensitive information.

4. Not Checking Cookie Existence

Always use isset() before accessing cookies.

Conclusion

PHP cookies allow websites to store small pieces of information in the user’s browser. They are useful for remembering user preferences, maintaining login states, and personalizing user experiences. However, since cookies are stored on the client side, developers must be careful not to store sensitive data in them.

Related PHP Tutorials