Cookies code not working

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
esoftsolz
Forum Newbie
Posts: 3
Joined: Sat Feb 25, 2012 8:34 pm

Cookies code not working

Post by esoftsolz »

Code: Select all

<html>
<head>
<title>!..CookiePage..!</title>
</head>
<body>
<?php
$expire=time()+(3600*24*30);
if((!ISSET($_COOKIE["user"]))&&(!ISSET($_COOKIE["no_of_times"])))
{
setcookie("user","Rajesh",$expire);
}
else
{
echo"Welcome".$_COOKIE["user"]."..!<br/>";
}?>
</body>
</html>
Above is the php code I have written. It is not showing the desired output. Instead it shows an error as below
"Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\xampp\practice\cookies.php:6) in C:\xampp\htdocs\xampp\practice\cookies.php on line 10" I am a PHP learner. Can any PHP expert help me here.

with regards
esoftsolz
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Cookies code not working

Post by califdon »

That's right. Once your script has sent anything to the browser, you cannot use setcookie() function. It must be used before anything like <html>, even a space or a blank line, has been sent. Refer to the manual:
http://php.net/manual/en/function.setcookie.php
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Cookies code not working

Post by flying_circus »

Califdon is technically correct, but I have found that it doesnt always work well with the design of my code. You can also use output buffering to tackle this problem. Check out the php manual for ob_start()
esoftsolz
Forum Newbie
Posts: 3
Joined: Sat Feb 25, 2012 8:34 pm

Re: Cookies code not working

Post by esoftsolz »

Thanks for your help. It works now. :)
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Cookies code not working

Post by califdon »

flying_circus wrote:Califdon is technically correct, but I have found that it doesnt always work well with the design of my code. You can also use output buffering to tackle this problem. Check out the php manual for ob_start()
Thanks, flying_circus, I always forget that, because I seldom use output buffering. Actually, I don't use cookies very much. There are so many things to remember!! :wink:
Post Reply