Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a cookie after output has been send to browser

Tags:

php

cookies

Is there a way that I can set a cookie after an html output? According to PHP manual setcookie() should be set before the output.

I need it for my voting system wherein a cookie will be set after a successful Mysql query. I made it in one file.

like image 451
user874737 Avatar asked Sep 18 '11 06:09

user874737


4 Answers

you can use the output buffers so at the top of your script you add ob_start() and this will create a buffer and you can then set the cookie and then end the buffer and flush out to the browser.

ob_start();
/* set cookie */
ob_end_flush();
like image 116
bigkm Avatar answered Nov 07 '22 12:11

bigkm


Is there a way that I can set a cookie after an html output?

Technically no. If you would like to set a cookie you need to ensure that no output has been send to the browser so far.

According to PHP manual setcookie() should be set BEFORE the output.

That's correct, otherwise it won't work. So I would even say must, not only should.

I need it for my voting system wherein a cookie will be set after a successful mysql query.

A successful mysql query on it's own will not create any output. Only a failed mysql query would if error reporting is enabled. So I wonder if you actually ran into a concrete problem or not.

The mysql query itself should not prevent you from using setcookie.

In case you have done already HTML output prior the use of setcookie you need to find the place where your HTML output started. Above that line place the ob_startDocs function which will start output buffering.

With output buffering enabled, your program can still "output" HTML but it will not be send immediately. Then you should be able to call setcookie with no problems:

<?php ob_start(); ?>
<html><body>
<?php 
  $result = mysql_run_query($query);
  echo '<h1>Your Voting Results</h1>';
  output_voting_result($result);
  set_cookie('vote', $result['id']);
?>
</body></html>

The output buffer will be automatically send to the browser when your script finishes, so there is not much more you need to care about, the rest works automatically.

like image 45
hakre Avatar answered Nov 07 '22 11:11

hakre


Cookies can be set in JavaScript on the client side - see this link for examples: http://www.w3schools.com/js/js_cookies.asp

like image 39
Barry Kaye Avatar answered Nov 07 '22 10:11

Barry Kaye


No. Cookies are sent in the header so they must be set before the output body begins.

You can, however, use PHPs built-in buffering so it won't actually generate any output until the script has completely finished executing.

ob_start is the function you want.

like image 44
Cameron Skinner Avatar answered Nov 07 '22 10:11

Cameron Skinner