tags:

views:

391

answers:

2

I created this simple script which will either set a cookie with three values or retrieve the cookies values if they are already set. On my server running PHP4, everything works. On my server with PHP 5 (5.2.11), the script fails to set the cookie in the browser. I already checked if output buffering is enabled in my php.ini and it is. Does anyone have any ideas as to why this fails to work?

<?php 
echo "<!DOCTYPE html>";
echo "<body>";
if (!isset($_COOKIE['taeinv'])) {
    echo "No cookie set...   Attempting to set a new cookie.";
    $user = "testuser";
    $role = "admin";
    $expire = "true";
    $halfHour = 1800;
    setcookie("websitename[Expire]", $expire, time()+$halfHour);
    setcookie("websitename[User]", $user, time()+$halfHour);
    setcookie("websitename[Role]", $role, time()+$halfHour);
}
if (isset($_COOKIE['websitename'])) {
    echo "Cookie Values:";
    echo "<br />";
        foreach ($_COOKIE['websitename'] as $name => $value) {
            echo "<b>$name</b> : $value <br />\n";
        }
}
echo "<br />";
echo "<a href=logout.php>Logout</a>";
echo "</body>";
echo "</html>";
?>
+1  A: 

You have to set the cookie before any output to the browser. Try moving all echo lines somewhere below the setcookie call. You could do something like this:

<?php
$set = false;
if (!isset($_COOKIE['taeinv'])) {
    $set = true;
    $user = "testuser";
    $role = "admin";
    $expire = "true";
    $halfHour = 1800;
    setcookie("websitename[Expire]", $expire, time()+$halfHour);
    setcookie("websitename[User]", $user, time()+$halfHour);
    setcookie("websitename[Role]", $role, time()+$halfHour);

}
echo "<!DOCTYPE html>";
echo "<body>";
if ($set) {
    echo "No cookie set...   Attempted to set a new cookie.";
}
if (isset($_COOKIE['websitename'])) {
    echo "Cookie Values:";
    echo "<br />";
        foreach ($_COOKIE['websitename'] as $name => $value) {
            echo "<b>$name</b> : $value <br />\n";
        }
}
echo "<br />";
echo "<a href=logout.php>Logout</a>";
echo "</body>";
echo "</html>";
?>
Tomas Markauskas
A: 

That worked on my old PHP4 server, but not on PHP5.

Brandon C
Don't add comments as new answers. Instead write comments to answers. What is the error message? Do you have any spaces before the opening `<?php` tag? You also might have an invisible UTF-8 BOM if there are no spaces or other symbols.
Tomas Markauskas
No spaces before the <?php tag
Brandon C
I just removed the original file and copy and pasted the code to a new file in nano in the terminal. It still fails to set the cookie.
Brandon C
Do you get any errors?
Tomas Markauskas
No errors in my logs.
Brandon C