I want a help on creation of cookies....
How to create a cookies and how to access that cookie information???
Plz help me!!!
Wen i use setcookie(name,value,expiry);
It's giving an error tht "Cannot modify header information - headers already sent by"
Last edited by tlife143; 07-03-2009 at 12:40 PM.
█ Garrett Royce | Generally Helpful Member
█ `ord(103)`@gjr.gr
█ I promise not to try not to mess with your mind
█ Tech Support | Programming Help | Flow Chart Tutorial
simply put, setcookie() must be used before ANYTHING is output to the page.
for example, the following will not work because there is a newline before the PHP engine is engaged:
The following will work however, despite it not being the first bit of code (because nothing else was output before it):PHP Code:
<?php
setcookie(name,1,time()+3600);
?>
PHP Code:<?php
if (isset($_GET['name']))
$name = $_GET['name'];
else $name=0;
if (isset($_GET['age']))
$age = $_GET['age'];
$calcage = $age+5;
if ($name)
$output = "$name, in 5 years you will be $calcage years old!";
else
$output = 'please submit name & age';
setcookie(name,1,time()+3600);
echo $output;
?>
If anyone can see it, my post was meant for anyone who reads it. Don't take it personally or think I'm being condescending... :nuts:
Modifying headers, such as locations and cookies, must be done before any output because the headers are sent as soon as you write to the page, as already said. That is why I find it helpful to put the body of php before everything, and use output control functions to write what has been written to after the body tag, shown below.
That way if there is an error anywhere on the page, you could better handle it. You could even redirect a user to an error page. Otherwise, you would have to be worried about where the error occurred.PHP Code:<?php
function ErrorHandler() {
$flags = "There has been an error!";
}
set_error_handler("ErrorHandler", E_ALL);
ob_start();
//PHP Code writes body.
$html = ob_get_clean();
ob_end_clean();
?>
<html><head><title>Bla</title></head><body>
<?php
if (isset($flags)) {
echo "<div style=\"color: red; height: 400px;\">" . $flags . "</div>";
}
echo $html;
?>
</body>
</html>
Last edited by Twinkie; 07-03-2009 at 05:13 PM.
$_COOKIE["name"] contains the data in a cookie with the name "name". This information is not available when the cookie has just been set. In other words, the page has to be reloaded for $_COOKIE to be updated.Originally Posted by tlife143
Real programmers don't document their code - if it was hard to write, it should be hard to understand.
Completely not true. ob_start() will simply prevent anything being output, and instead saves everything until it is flushed.
In my example I saved a string to a variable and then output that, basically performing the same function.
You can get away with NEVER using ob_start, and still create cookies.
If anyone can see it, my post was meant for anyone who reads it. Don't take it personally or think I'm being condescending... :nuts: