in reply to Cookie question

Cookies are set in the headers which have to be sent to the web browser before anything else, so of course that doesn't work.

Scent of an XY Problem aside, consider rearranging the order you do things in your code. Do all your computation / frobnication / examination of inputs first, then send whatever reply you're going to send (including the conditional cookie) at the end.

The cake is a lie.
The cake is a lie.
The cake is a lie.