How to Check if Cookie is Set in PHP: Simple Guide
In PHP, you can check if a cookie is set by using the
isset() function on the $_COOKIE superglobal array with the cookie's name. For example, isset($_COOKIE['cookie_name']) returns true if the cookie exists and false if it does not.Syntax
To check if a cookie is set, use the isset() function with the $_COOKIE array and the cookie's name as the key.
isset(): Checks if a variable is set and notnull.$_COOKIE: A PHP superglobal array that stores all cookies sent by the browser.'cookie_name': The name of the cookie you want to check.
php
isset($_COOKIE['cookie_name'])Example
This example shows how to check if a cookie named user is set and prints a message accordingly.
php
<?php if (isset($_COOKIE['user'])) { echo "Cookie 'user' is set with value: " . $_COOKIE['user']; } else { echo "Cookie 'user' is not set."; } ?>
Output
Cookie 'user' is not set.
Common Pitfalls
Common mistakes when checking cookies include:
- Checking the cookie before it is actually set by the browser (cookies are sent on the next request).
- Using
empty()instead ofisset(), which can give false negatives if the cookie value is "0" or empty string. - Not considering cookie expiration or path, which can affect availability.
php
<?php // Wrong way: using empty() can fail if cookie value is '0' if (!empty($_COOKIE['user'])) { echo "Cookie 'user' is set."; } else { echo "Cookie 'user' is not set or empty."; } // Right way: use isset() to check existence if (isset($_COOKIE['user'])) { echo "Cookie 'user' is set."; } else { echo "Cookie 'user' is not set."; } ?>
Output
Cookie 'user' is not set or empty.
Cookie 'user' is not set.
Quick Reference
Summary tips for checking cookies in PHP:
- Use
isset($_COOKIE['name'])to check if a cookie exists. - Remember cookies are available only on the next page load after setting.
- Do not rely on
empty()for existence checks. - Check cookie path and domain if cookies seem missing.
Key Takeaways
Use isset($_COOKIE['cookie_name']) to check if a cookie is set in PHP.
Cookies are only available on the next request after they are set.
Avoid using empty() to check cookies because it can misinterpret valid values.
Always consider cookie path, domain, and expiration when troubleshooting.
$_COOKIE is a superglobal array holding all cookies sent by the browser.