0

Possible Duplicate:
“Header Already Sent” error in PHP

I have my code so that the user specifies their IGN (Ingame Name) And then stores it in a cookie. It will not work though.

<form action="index.php" method="GET">
    Minecraft IGN:
    <input type="text" name="ign">
    <input type="submit" value="Submit">
</form>

<?PHP
error_reporting(0);
$player = $_GET["ign"];
$exp = time()+86400;
setcookie("ign", $player, $exp, "/", "", "");

if (isset($player)) {
    echo "Your Minecraft Ingame Name Was Set To $player!";
}
?>

<br>

<?PHP
if (isset($player)) {
    echo '<p>Click <a href="http://gophobia.com/phpsend/">Here</a> To Redeem Ur Prizes    :3</p>';
}
echo '<br />';
print_r($_COOKIE);
?>
Community
  • 1
  • 1
Necrohhh
  • 223
  • 2
  • 8
  • 13
  • Fixed. Sorry. That is the ingame name I was trying to set, I tried it manually no dice. Its now set back to $player – Necrohhh Aug 28 '12 at 16:01

2 Answers2

2

This is a very common mistake but an easy one to fix.

This is straight from the manual but says it better than I ever could:

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace.

http://php.net/manual/en/function.setcookie.php

The key is that it must be called before any output.

Jared
  • 12,406
  • 1
  • 35
  • 39
  • 2
    Also to remember: Cookie gets set on the client side. It isn't visible on the server until the client sends a request back to the server with the cookie as part of the request. Therefore: it won't show up in $_COOKIE until you make another page load after it has been set. – bencoder Aug 28 '12 at 16:06
  • This worked for me =]. Thanks a bunch. I knew it was something silly :D – Necrohhh Aug 28 '12 at 16:37
1

Your code may be working well. The script sets the cookie when the page loads. But you have to page the load again to retrieve the value since both setting cookie and retrieving its value cannot work in a single instance.

Alfred
  • 21,058
  • 61
  • 167
  • 249