Nik
Nik

Reputation: 5

setcookie not working 3

I am trying to set a cookie based on the returned value from an insert into mySQL. I know the insert has worked as I have a value for mysqli_insert_id($link). However, he cookie is the same before and after I attempt to run setcookie. Can anyone help? The code I am using is

echo mysqli_insert_id($link)."<br>";
print_r($_COOKIE); 
echo "<br>";
setcookie("id", mysqli_insert_id($link), time() + 60*60*24);
print_r($_COOKIE);
echo "<br>";

Upvotes: 1

Views: 72

Answers (1)

Blue
Blue

Reputation: 22911

setcookie() needs to be sent before anything is echoed out to the body of the page. For example:

echo 'test'; //At this point, headers are done, and the body has started
setcookie(...); //Fails

An alternative solution would be to use ob_start() to buffer the output into memory before outputting to the browser. You can do something like this:

ob_start();
echo 'test'; //Output is captured, and stored in memory
setcookie(...); //Nothing has been output yet, so header is set properly

ob_end_flush(); //We're done storing stuff in the buffer, output it to the browser.

Upvotes: 3

Related Questions