Docs/PHP/Cookies

PHP Cookies

Cookie menyimpan data kecil di browser user.

Functions

  • setcookie(name, value, expire, path)
  • $_COOKIE['name'] — baca cookie

Perbedaan Session vs Cookie

  • Session: di server, lebih aman, expire saat browser tutup
  • Cookie: di browser, bisa diset expire, max 4KB
index.php
Try It →
<?php
// Set cookie (expire 30 hari)
setcookie("theme", "dark", time() + (30 * 24 * 60 * 60), "/");
setcookie("language", "id", time() + (365 * 24 * 60 * 60), "/");

// Read cookies
$theme = $_COOKIE['theme'] ?? 'light';
$lang = $_COOKIE['language'] ?? 'en';

echo "Theme: $theme
";
echo "Language: $lang

";

// Check cookie
if (isset($_COOKIE['theme'])) {
    echo "✅ Theme cookie exists
";
}

// Delete cookie (set expire to past)
// setcookie("theme", "", time() - 3600, "/");
echo "
// Delete: setcookie('theme', '', time()-3600, '/')";
?>