0

Trying to figure out why I don't get any output for this script. I get this error:

Warning: Cannot modify header information - headers already sent by (output started at /Library/WebServer/Documents/WEBB_SERVER/4.2x/index.php:38) in /Library/WebServer/Documents/WEBB_SERVER/4.2x/index.php on line 23

Warning: Cannot modify header information - headers already sent by (output started at /Library/WebServer/Documents/WEBB_SERVER/4.2x/index.php:38) in /Library/WebServer/Documents/WEBB_SERVER/4.2x/index.php on line 25

I'm intending to print the name of the cookie and the time when it was saved. I know that the error warns me that there possibly is a blank space somewhere before/after the PHP tag, but cannot find the problem.

And why is my output not showing? Name ("Cookie monster") and the time. I assume this has to do with the warnings.

Any advice appreciated!

<?php

class cookie {
    
    /* Konstruktor som skriver ut information om kakor - finns det inga så skapas dem */

    public function __construct() {

        if (isset($_COOKIE['time']) && isset($_COOKIE['name'])) {
            echo "Name of cookie: " . $_COOKIE['name'];
            echo "</br>";
            echo "Time of creeation: " . $_COOKIE['time'];
        } else {
            $this -> SetCookie();
        }
    }

    /* Funktion för att skapa cookies */

    public function SetCookie() {
        $expire = time() + 60 * 60 * 3;
        $now = @date("Y-m-d H:i:s");
        setcookie('time', $now, $expire);
        $_COOKIE['time'] = $now;
        setcookie('name', "Cookie monster", $expire);
        $_COOKIE['name'] = "Cookie monster";
    }

}
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <?php
        $t = new cookie();
        ?>
    </body>
</html>
Community
  • 1
  • 1
Dolcens
  • 6,201
  • 2
  • 12
  • 12

1 Answers1

1

You can't set any cookies after you print anything, because setcookie parameter is being send back in the request headers, so if you print anything than you can't set any cookies. try this:

<?php

class cookie {

/* Konstruktor som skriver ut information om kakor - finns det inga så skapas dem */

public function __construct() {

    if (isset($_COOKIE['time']) && isset($_COOKIE['name'])) {
        echo "Name of cookie: " . $_COOKIE['name'];
        echo "</br>";
        echo "Time of creeation: " . $_COOKIE['time'];
    } else {
        $this -> SetCookie();
    }
}

/* Funktion för att skapa cookies */

public function SetCookie() {
    $expire = time() + 60 * 60 * 3;
    $now = @date("Y-m-d H:i:s");
    setcookie('time', $now, $expire);
    $_COOKIE['time'] = $now;
    setcookie('name', "Cookie monster", $expire);
    $_COOKIE['name'] = "Cookie monster";
    }
}
$t = new cookie();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <? echo $t; ?>
</body>
</html>
MoJo
  • 44
  • 7