Help With PHP And Cookies

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
dmiller
Forum Newbie
Posts: 2
Joined: Wed Jul 26, 2006 11:51 am

Help With PHP And Cookies

Post by dmiller »

I've been having a hell of a time trying to figure out how to implement what I thought was a simple PHP script to save a username in a cookie so it would be displayed each time the user returns. Here is the code:

Code: Select all

<?php
	if (isset($_COOKIE['megacookie']))
	{
		echo "Hello, ".$_COOKIE['megacookie']."!";
	}
	else
	{
		include('cook.php');
		if (isset($_GET['names']))
		{
			setcookie("megacookie",$_GET['names'],time()+60*60*24*365);
		}
	}
?>
And the contents of cook.php...

Code: Select all

<form action="reflex.php" method="get">
Go Away:<input type="text" name="names" size="10" maxlength="20" value="">
<input type="submit" value="Press">
</form>

I have seen plenty of example online of using forms and cookies to save information, but I keep getting an error saying "Cannot modify header information - headers already sent". I've read a little about what this means, but I've seen many different explanations and none seemed to help. Any help would really be appreciated. Thanks.
Last edited by dmiller on Wed Jul 26, 2006 12:12 pm, edited 1 time in total.
User avatar
daedalus__
DevNet Resident
Posts: 1925
Joined: Thu Feb 09, 2006 4:52 pm

Post by daedalus__ »

Headers already sent means that there has already been stuff output to the page.

You have to start sessions and set cookies BEFORE anything has been sent to the browser.

Also, could you please use

Code: Select all

tags when posting PHP?
dmiller
Forum Newbie
Posts: 2
Joined: Wed Jul 26, 2006 11:51 am

Post by dmiller »

Sorry about the PHP tags.

Anyway, how exactly would I use sessions to set the cookies before anything is sent to the browser? As you can probably tell I'm a complete neophyte when it comes to PHP (I just started learning it this past week) so I really don't know where to start sessions.
User avatar
daedalus__
DevNet Resident
Posts: 1925
Joined: Thu Feb 09, 2006 4:52 pm

Post by daedalus__ »

Well, just for some general info make sure you read plenty in the manual, which you can download from http://www.php.net. Use tons of Google. Post here when you are stuck.


You don't use sessions to set cookies, but when you set a cookie, it has to be before any output to the browser.

Try this:

Code: Select all

// If there are names, put them in the cookie before output
if (isset($_GET['names'])) 
{ 
	setcookie("megacookie",$_GET['names'],time()+60*60*24*365); 
}
// output
include('cook.php');
// if the cookie is set, say hello!
if (isset($_COOKIE['megacookie']) == FALSE)
{
	echo "Hello, ".$_COOKIE['megacookie']."!"; 
}
Post Reply