Cookies are sent in the headers of the transmission of the HTTP page. Once you give some output, you cannot modify these anymore.
The problem in your case lies in you outputting some of the HTML-document before trying to set the cookie.
There are a few ways to solve it; one of which is setting the cookie prior to outputting anything on the page like so
Alternatively, you could buffer your output so that nothing gets written until you explicitly tell it to
For more information on this last approach, take a look at the ob_start and ob_end_flush functions.
It might be useful to read about setcookie, too.