0
0
PhpHow-ToBeginner · 3 min read

How to Set Cookie in PHP: Simple Guide with Examples

In PHP, you set a cookie using the setcookie() function before any output is sent to the browser. You provide the cookie name, value, and optional parameters like expiration time to store data on the user's browser.
📐

Syntax

The setcookie() function sets a cookie with several optional parameters:

  • name: The name of the cookie.
  • value: The value stored in the cookie.
  • expire: When the cookie expires (timestamp). Default is session cookie.
  • path: The path on the server where the cookie is available.
  • domain: The domain that can access the cookie.
  • secure: If true, cookie is sent only over HTTPS.
  • httponly: If true, cookie is accessible only through HTTP(S), not JavaScript.
php
bool setcookie(string $name, string $value = "", int $expire = 0, string $path = "", string $domain = "", bool $secure = false, bool $httponly = false);
💻

Example

This example sets a cookie named user with value John that expires in 1 hour. It then shows a message confirming the cookie is set.

php
<?php
// Set cookie before any output
setcookie("user", "John", time() + 3600); // expires in 1 hour

if (isset($_COOKIE["user"])) {
    echo "Cookie 'user' is set with value: " . $_COOKIE["user"];
} else {
    echo "Cookie 'user' is not set yet.";
}
?>
Output
Cookie 'user' is not set yet.
⚠️

Common Pitfalls

Common mistakes when setting cookies in PHP include:

  • Calling setcookie() after outputting HTML or echoing text, which causes headers to be sent and cookie setting to fail.
  • Not setting an expiration time, which makes the cookie a session cookie that disappears when the browser closes.
  • Forgetting to check if the cookie exists before reading it.
php
<?php
// Wrong: output before setcookie
// echo "Hello";
// setcookie("test", "value"); // This will fail

// Right way:
setcookie("test", "value", time() + 3600);
echo "Cookie set successfully.";
?>
Output
Cookie set successfully.
📊

Quick Reference

Remember these tips when working with cookies in PHP:

  • Always call setcookie() before any output.
  • Use time() + seconds to set expiration.
  • Use $_COOKIE superglobal to read cookies.
  • Set httponly to true for security against JavaScript access.
  • Use secure flag to send cookies only over HTTPS.

Key Takeaways

Use setcookie() before any output to set cookies successfully.
Set expiration time with time() + seconds to control cookie lifetime.
Access cookies using the $_COOKIE superglobal array.
Use secure and httponly flags to improve cookie security.
Check if a cookie exists before using its value.