PHP setcookie() Function: Everything You Need to Know
As a PHP developer, you may need to set cookies for your web application to store information on the client side. The setcookie() function is a built-in
As a PHP developer, you may need to set cookies to store information on the client side. The setcookie() function is a built-in PHP function that handles this. In this article, we cover its modern syntax, how to set, read, and delete cookies, the most common gotchas, and when to reach for sessions instead.
What is the setcookie() Function?
The setcookie() function is a PHP built-in function that sends a Set-Cookie HTTP header to the browser, asking it to store a small piece of data. On the next request the browser sends that data back, which is how a stateless protocol like HTTP can "remember" things between page loads — for example a "remember me" token, a language preference, or a tracking ID.
Because a cookie is an HTTP header, setcookie() must run before any output is sent to the browser. The cookie itself does not become available immediately; it appears in the $_COOKIE superglobal only on the next request, once the browser has sent it back.
How to Use the setcookie() Function
Using the setcookie() function is straightforward. The array-based options syntax was introduced in PHP 7.3. In PHP 8.1, the legacy seven-parameter positional syntax was deprecated. Here is the modern syntax:
The PHP syntax of setcookie() Function
setcookie($name, $value, $options);The $options parameter is an associative array that accepts the following keys:
expires: The expiration time of the cookie (Unix timestamp).path: The path on the server in which the cookie will be available.domain: The domain on which the cookie will be available.secure: Whether the cookie should be transmitted over HTTPS only.httponly: Whether the cookie should be accessible only through HTTP.samesite: Restricts the cookie to same-site requests. Accepts'Strict','Lax', or'None'. Note: when you use'None', you must also setsecuretotrue, or modern browsers will reject the cookie.
If you omit expires (or set it to 0), the cookie becomes a session cookie — it lives only until the browser is closed. Setting expires to a future timestamp turns it into a persistent cookie that survives browser restarts.
Here is an example of how to use the setcookie() function to set a cookie:
How to Use the setcookie() Function?
<?php
$options = [
'expires' => time() + (86400 * 30), // 30 days
'path' => '/',
'domain' => '.example.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
];
setcookie('username', 'john', $options);In this example, we use the setcookie() function to set a cookie named username with the value john. We also specify the expiration time as 30 days from the current time, the path on the server as /, the domain as .example.com, and set the secure, httponly, and samesite flags to ensure the cookie is only transmitted over HTTPS, is not accessible through client-side scripting, and is restricted to same-site requests, respectively.
Reading Cookies
Cookies set with setcookie() are automatically available in the $_COOKIE superglobal array on subsequent page requests. You can check for their existence and read their values like this:
if (isset($_COOKIE['username'])) {
echo "Welcome, " . htmlspecialchars($_COOKIE['username']);
}Deleting Cookies
To delete a cookie, you must set its expiration time to a past timestamp. The value can be left empty.
setcookie('username', '', [
'expires' => time() - 3600,
'path' => '/',
]);Make sure the path (and domain, if you set one) match the values you used when creating the cookie. A cookie set with path => '/admin' will not be deleted by a call that uses path => '/', because the browser treats them as different cookies.
Important Notes
- Return Value:
setcookie()returnstrueon success andfalseon failure (including when headers are already sent). - Headers Already Sent: Cookies must be set before any output is sent to the browser (including HTML, whitespace before
<?php, orecho). Otherwise, PHP will throw a "Headers already sent" warning. See headers_sent() to detect this case. - Automatic Encoding:
setcookie()automatically URL-encodes cookie values, so manual encoding is usually unnecessary. If you need to store a value verbatim without encoding, use setrawcookie() instead. - Size limits: Browsers cap each cookie at roughly 4 KB and limit how many cookies a single domain may store, so cookies are meant for small values, not bulk data.
Cookies vs. Sessions
Cookies live in the browser and are sent with every request, so anything you store is visible to (and editable by) the user. For sensitive data, store only an identifier in the cookie and keep the real data server-side with PHP sessions. For a broader overview of cookie handling in PHP, see the PHP Cookies chapter.
Conclusion
The setcookie() function is a useful tool for setting cookies in your PHP web application. By understanding the modern array syntax, setting it before any output, and matching path/domain when deleting, you can reliably manage client-side data — and you know when to reach for sessions instead.