How to Get Cookie in PHP: Simple Guide with Examples
In PHP, you get a cookie value using the
$_COOKIE superglobal array with the cookie's name as the key, like $_COOKIE['cookie_name']. Make sure the cookie exists before accessing it to avoid errors.Syntax
To get a cookie value in PHP, use the $_COOKIE array with the cookie's name as the key.
$_COOKIE: A built-in PHP array holding all cookies sent by the browser.'cookie_name': The name of the cookie you want to retrieve.
php
<?php // Access a cookie named 'user' if (isset($_COOKIE['user'])) { $user = $_COOKIE['user']; } else { $user = 'Guest'; } echo $user; ?>
Example
This example shows how to check if a cookie named username exists and then prints its value. If the cookie is not set, it prints a default message.
php
<?php // Example to get a cookie value if (isset($_COOKIE['username'])) { echo 'Hello, ' . $_COOKIE['username'] . '!'; } else { echo 'Hello, Guest!'; } ?>
Output
Hello, Guest!
Common Pitfalls
Common mistakes when getting cookies in PHP include:
- Trying to access a cookie without checking if it exists, which causes warnings.
- Expecting the cookie to be available immediately after setting it; cookies are sent by the browser on the next request.
- Not considering cookie expiration or path, which can affect availability.
php
<?php // Wrong way: Accessing cookie without checking // echo $_COOKIE['user']; // May cause warning if 'user' cookie is not set // Right way: Check before accessing if (isset($_COOKIE['user'])) { echo $_COOKIE['user']; } else { echo 'User cookie not set'; } ?>
Quick Reference
| Action | Code Example |
|---|---|
| Check if cookie exists | isset($_COOKIE['cookie_name']) |
| Get cookie value | $value = $_COOKIE['cookie_name']; |
| Handle missing cookie | if (isset($_COOKIE['cookie_name'])) { /* use cookie */ } else { /* fallback */ } |
Key Takeaways
Use $_COOKIE['cookie_name'] to get a cookie value in PHP.
Always check with isset() before accessing a cookie to avoid warnings.
Cookies set in PHP are available on the next page load, not immediately.
Cookie availability depends on path and expiration settings.
Use fallback values when cookies might not be set.