Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

setcookie

Sends a cookie to the browser.

Syntax

setcookie(string $name, string $value = "", array $options = []): bool

Parameters

ParameterTypeDescription
$namestringThe cookie name.
$valuestringOptional. The value.
$optionsarrayOptional. `expires`, `path`, `secure`, `httponly`, `samesite`.

Return value

bool`true` if the header was sent.

Examples

Remembering a theme for a year and removing a cookie:

<?php
 
setcookie('theme', 'dark', [
    'expires' => time() + 60 * 60 * 24 * 365,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);
 
setcookie('old_banner', '', ['expires' => time() - 3600, 'path' => '/']);

Notes

Call the function before any output: a cookie travels in the headers. The value appears in $_COOKIE only on the next request.

See also

  • session_start — Starts a session or resumes the existing one.
  • header — Sends an HTTP response header.
  • time — Returns the current timestamp.

Related recipes

In the tutorial

  • Sessions and cookies — Sessions and cookies in PHP — remembering a visitor between requests, session_start, $_SESSION and setcookie.

Thanks for reading!

Donate to the site — we work hard for you.