You have to call the setcookie() function before anything has been output to the webbrowser - in your code, the following will have already been outputted to the browser before your call to setcookie():
Additionally, if you have any html (or just blank lines) prior to the setcookie() function, that would also cause that error.
One way around this if you don't want to rearrange your code is to call the function: ob_start() at the beginning of your script to turn on output buffering (nothing is sent to the browser until the script ends, or you call ob_end_flush() )
for more info.
Hope that helps