Search⌘ K
AI Features

Cookies Are Headers

Explore how PHP cookies function as HTTP headers and how to set them correctly using setcookie(). Understand why cookies become available only on the next request and learn best practices to avoid errors when modifying headers after output starts.

Set-Cookie header and Cookie header

Personally, I’ve had a lot of trouble understanding cookies and how to use them correctly. That’s because I didn’t realize they were headers. When you call setcookie(), the result is not some magic cookie (whatever that is), but a Set-Cookie response header. Only when the browser has received the response from the server, it will process the Set-Cookie headers of the response and keep the provided values in its own storage facility. The next time it makes a request to your server, it will look in that same storage facility for any cookies that should be sent to the server as a Cookie header on the request. The following diagram illustrates this process of setting a cookie ...