views:

57

answers:

5

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?

UPDATE:

I do this before the setCookie part:

$ad_id=$_GET['ad_id'];
$query2 = "SELECT * FROM classified WHERE classified.ad_id = '$ad_id'";
$results2 = mysql_query($query2) or die(mysql_error());
$row2 = mysql_fetch_array($results2);
$cat = $row2['category'];
$action=$row2['action'];
$sql_table='';
$num_rows = mysql_num_rows($query_results);
if ($num_rows != 0){
   HERE COMES THE SETCOOKIE PART
A: 

Make sure that you do not print anything prior to adding header-based information (as cookies are).

Sean Kinsey
check my update please...
Camran
+2  A: 

The restriction is not that you must not do anything before setting your cookies, merely that you must no output anything before setting your cookies.

For example, let's say we want to get some data from the database, output it to the user and set it to the cookie.

<?php
$data = getDbData();
echo $data['field'];
setcookie('field', $data['field'], time()+86400, '/');

This will fail because we've output the data before setting the cookie. We can fix it by moving the output to after we set the cookie.

<?php
$data = getDbData();
setcookie('field', $data['field'], time()+86400, '/');
echo $data['field'];
Rob Young
What counts as an output then? Is mysql_query($query) an output? Check my edit please...
Camran
Anything that causes data to be sent to the browser, so that could be echo or print statements or stuff outside the PHP tags.
Rob Young
None of the code you have put in your edit counts as output. Check that you don't have anything else above the code that you have pasted, and check for any spaces/blank lines that might exist *before* the opening `<?php` tag.
Blair McMillan
I tend to create a object called Output with methods like addCookie(),addHeader() etc and then when im ready to send my content i will do $ouput->addCookie('test','value',time()+1000,'/'); $output->send($html);.
RobertPitt
A: 

I can't see any problems with the code, unless mysql outputs an error, which could cause this.

This is a shot in the dark, but make sure you don't have any whitespace (or anything else for that matter) before the opening php tags. Also make sure you don't have any trailing whitespaces after the closing php tags in the files you include.

mqchen
+4  A: 

As others have suggested, make sure, you are not outputting any html or whitespace before you set your cookie.

This will fail because you are printing html before you set your cookie.

<p>
<?php
  // your cookie code - note <p> tag before <?php tag
  // ...
?>

This will also fail, because you are printing whitespace before you set your cookie.

 
<?php
  // your cookie code - note the extra linebreak before <?php tag
  // ...
?>

Also

 <?php
  // your cookie code - note the extra space before <?php tag
  // ...
?>

If you use an UTF encoding for your php script (and if you are not in one of the english speaking countries, chances are that you do), make sure your editor is set that it does not include byte order mark (BOM) at the begining of every file. See http://en.wikipedia.org/wiki/Byte_order_mark for more detail on BOM.

Luc
Very good point with the Byte Order Mark, I had this issues a few days back when i was using an inbuilt editor on my FTP Client to do quick edits to some code, make sure you turn of the BOM, this can cause alot of trouble with design and valid XHTML/HTML5 etc, but also affecting your actual php core files.
RobertPitt
Great point the BOM... That was the exact problem... Thanks
Camran
+1  A: 

The error message you showed us says that the headers were sent on the setcookie() line. Thus, you may be setting headers or cookies later in the code, which is causing the error. (Or so I believe, since I can't recall the error word for word and you cut it off at the critical point)

waiwai933