PHP : Cookies

Cookies in PHP are used to store small pieces of data on the client's computer. They are commonly used for sessions, personalization, tracking, and more. Here's a guide on how to work with cookies in PHP:

Setting Cookies:

You can set a cookie using the setcookie() function. It takes several parameters, but the most commonly used ones are the name, value, expiration time, and path.


// Set a cookie named "user" with value "John Doe"
setcookie("user", "John Doe", time() + 3600, "/"); // Expires in 1 hour, available on the entire domain

 

  • The time() function returns the current Unix timestamp.
  • time() + 3600 sets the cookie to expire in 1 hour (3600 seconds).
  • The last parameter "/" sets the cookie's availability to the entire domain.

Retrieving Cookie Values:

You can retrieve cookie values using the $_COOKIE superglobal.


// Check if the "user" cookie is set
if(isset($_COOKIE["user"])) {
    echo "Welcome " . $_COOKIE["user"] . "!";
} else {
    echo "Cookie not set!";
}

 

Modifying Cookies:

To modify a cookie, you can set a new cookie with the same name.


// Modify the "user" cookie's value
setcookie("user", "Jane Smith", time() + 3600, "/");

 

Deleting Cookies:

To delete a cookie, set its expiration time to a past value.


// Delete the "user" cookie
setcookie("user", "", time() - 3600, "/");

 

Cookie Parameters:

  • Name: The name of the cookie.
  • Value: The value to be stored.
  • Expiration:Unix timestamp when the cookie should expire (if not set, it becomes a session cookie).
  • Path:The path on the server in which the cookie will be available.
  • Domain:The domain for which the cookie is available.
  • Secure:If true, the cookie will only be sent over secure (HTTPS) connections.
  • HttpOnly: If true, the cookie will be accessible only through the HTTP protocol.

Example:

Here's a simple example that sets, retrieves, modifies, and deletes a cookie:


// Set a cookie
setcookie("user", "John Doe", time() + 3600, "/");

// Retrieve and display the cookie
if(isset($_COOKIE["user"])) {
    echo "Welcome " . $_COOKIE["user"] . "!";
} else {
    echo "Cookie not set!";
}

// Modify the cookie
setcookie("user", "Jane Smith", time() + 3600, "/");

// Delete the cookie
setcookie("user", "", time() - 3600, "/");

echo "Cookie deleted.";
 

Session Cookies:

If you omit the expiration time, the cookie becomes a session cookie, which is deleted when the browser is closed.


// Set a session cookie
setcookie("session_cookie", "value"); // Expires when the browser is closed

 

Cookies are a convenient way to store small amounts of data on the client's computer, but remember not to store sensitive information in cookies as they are stored on the client side and can be manipulated.