Please keep in mind that if you call setcookie() several times during the script execution (even for the same name, domain and path), then Set-Cookie header will be sent several times, and only after receiving all of them, client browser will "merge" them, replacing first value for the cookie with the next etc.
This may cause very large headers length sometimes, so you'll have to either increase buffers for your web server; change your code logic to determine all possibly-changing parameters values right from the start; implement some sort of global Response object keeping all the data, including cookies as well, till the end of processing (sort of optimized output beffering); or just avoid storing any large data in cookies.