Superglobals · Lesson 6 of 8
$_COOKIE
Read browser cookies as untrusted input and set them with secure attributes.
Lesson
Cookies are sent by the browser and can be missing, modified, or replayed. Never store a plaintext password or trust a cookie as proof of authorization. Set expiry, path, Secure, HttpOnly, and SameSite options deliberately; use server-managed sessions for sensitive state.
Validate and escape cookie values just like other external input.
Further guidance
Superglobal values come from the request or process environment and can be missing or have an unexpected type. Check the key and shape before use, validate it for the operation, and avoid printing secrets or trusting client-controlled headers. Prefer the specific input source over merged request data.
Practice task: Create a fresh example for $_COOKIE. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
$_COOKIE
PHP
$theme = $_COOKIE['theme'] ?? 'light';
$allowed = ['light', 'dark'];
if (! is_string($theme) || ! in_array($theme, $allowed, true)) {
$theme = 'light';
}
echo $theme;
Expected output
light or dark
Key points
- Read browser cookies as untrusted input and set them with secure attributes.
- Treat request and environment values as untrusted input.
- Check the expected type and presence before using a value.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.