You must handle your cookies before anything is output to browser (including PHP error/notice messages)... before the headers are sent out. One way to ensure this is to use output buffering:
Code:
ob_start();
// whatever your code is to check db and information,
// validation, etc. Just dont' do anything that outputs
// anything just yet
setcookie(); // whatever
// now you can output
ob_flush(); // flush buffer