Creating cookies with setcookie()
Learn to create a cookie in the browser with setcookie().
What does setcookie() do?
HTTP is stateless: each request is independent of the previous one. Cookies let the browser remember data between requests. PHP creates a cookie with setcookie().
When called, PHP sends a Set-Cookie header. The browser stores the cookie and sends it back on later requests.
Call it before any output, at the top of the page; otherwise you get a headers already sent error.
Cookie name and value
setcookie() takes at least two arguments: a name and a value. Both are strings. The name identifies the cookie; the value is the data the browser stores.
Keep cookie names simple: no spaces, no special characters. Values should stay short; browsers usually allow about 4 KB.
Example: setcookie('lang', 'en') creates a cookie named lang with value en.
Exercise Create a cookie and confirm
Call setcookie() with first argument 'username' and second 'Alex'. Then echo created.
Show example solution
Call setcookie('username', 'Alex'), then echo "created".
Example solution:
<?php
// Call setcookie and print 'created'
setcookie('username', 'Alex');
echo "created\n";
Test yourself
-
When should setcookie() be called?
- At the very end, after all output
- Before any output, at the top of the page
- Only after a database connection
- On the same line as echo
Show answer
Before any output, at the top of the page — Correct. setcookie() is called before output, so it can be sent as a header.
-
Create the cookie from the config
<?php $cfg = ['user' => 'Alex']; ____ echo $cfg['user'];Show answer
<?php $cfg = ['user' => 'Alex']; setcookie('user', $cfg['user']); echo $cfg['user']; -
Match the parts of setcookie
- setcookie(name, value)
- Creates a cookie
- name
- The cookie name
- value
- The cookie value
- Browser
- Stores the cookie