Page 1 of 1

Help With PHP And Cookies

Posted: Wed Jul 26, 2006 11:55 am
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.

Posted: Wed Jul 26, 2006 12:02 pm
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?

Posted: Wed Jul 26, 2006 12:13 pm
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.

Posted: Wed Jul 26, 2006 12:19 pm
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']."!"; 
}