Problem with sending "SetCookie" first in php code

Posted by Camran on Stack Overflow See other posts from Stack Overflow or by Camran
Published on 2010-05-30T14:38:26Z Indexed on 2010/05/30 14:42 UTC
Read the original article Hit count: 136

Filed under:
|
|
|
|

According to this manual: http://us2.php.net/setcookie I have to set the cookie before anything else.

Here is my cookie code:

if (isset($_COOKIE['watched_ads'])){
    $expir = time()+1728000; //20 days
    $ad_arr = unserialize($_COOKIE['watched_ads']);
    $arr_elem = count($ad_arr);
    if (in_array($ad_id, $ad_arr) == FALSE){
        if ($arr_elem>10){
        array_shift($ad_arr);
        }
        $ad_arr[]=$ad_id;
        setcookie('watched_ads', serialize($ad_arr), $expir, '/');
    }
}
else {
    $expir = time()+1728000; //20 days
    $ad_arr[] = $ad_id;
    setcookie('watched_ads', serialize($ad_arr), $expir, '/');
}

As you can see I am using variables in setting the cookie.

The variables comes from a mysql_query and I have to do the query first. But then, if I do, I will get an error message:

 Cannot modify header information - headers already sent by ...

The error points to the line where I set the cookie above.

What should I do?a

© Stack Overflow or respective owner

Related posts about php

Related posts about JavaScript