I am working on a cookies first time. I set my cookies at the top of the HTML in header.php and its create cookie successfully
<?php
     $haystack = "http://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
     $needle = "/shop/?filter_results=true&widget_search=true&";
     if(strpos($haystack, $needle)){
          setcookie("link", $haystack);
     } else {
          if(strpos($haystack, "/shop/?filter_results=true&widget_search=true")){
               setcookie("link",NULL);
          }
     }
?>
<!DOCTYPE html>
<html>
But when i add my cookie in <head> tag the browser gives me
Warning: headers already sent by ......
I also try to add this code by wp_head hook but its not work. 
Please help me how can i set my cookie in head tag.
 
     
    