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.
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();
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_start
Docs 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.
Cookies can be set in JavaScript on the client side - see this link for examples: http://www.w3schools.com/js/js_cookies.asp
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With