Php setcookie crashes under php5

I created this simple script that will either set a cookie with three values, or receive cookie values ​​if they are already set. Everything works on my server with PHP4. On my server with PHP 5 (5.2.11), the script cannot 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 is not working?

<?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>";
?>
+3
source share
4 answers

You must set a cookie before any exit to the browser. Try moving all the lines echosomewhere below the call setcookie. You can 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>";
?>
+2
source

PHP4, PHP5.

0

- ob_start() ob_end_flush().

:

 <?php   ob_start();  echo '<p> ...  </p>';   setcookie ('myLanguage', 'PHP');    ob_end_flush();  //     PHP- ...
 ?>>
0

, Chrome . Firefox .

The installation of all parameters in the function is setcookiefixed.

This sets the cookie, but Chrome deletes the cookie with one click:

setcookie('uname', 'Joe', time()+3600*24);

This sets a cookie, and the browser saves it:

setcookie('uname', 'Joe', time()+3600*24, '/', 'www.domain.com', false, false);
0
source

Source: https://habr.com/ru/post/1731912/


All Articles