简体   繁体   中英

PHP 5.4.X is capable of placing setcookie() after HTML markups without “Headers already sent” warning?

I used to experience Warning: Cannot add header information - headers already sent when trying to place header() session_start() or setcookie() after echo or any HTML markups. But when I upgraded the PHP in my local server to 5.4.7 (in XAMPP 1.8.1 ), I don't encounter this warning anymore. Is this normal for PHP 5.4.X?

I tried placing setcookie() after some texts and an echo in this example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Cookie Test</title>
</head>
<body>
<h1>Cookie Test</h1>
<?php
    if (isset($_COOKIE['test'])) {
        echo "<p>{$_COOKIE['test']}</p>";
    } else {
        echo "<p>No cookie..</p>";
        setcookie('test', 'You have a cookie!', time()+300, '/');
    }
?>
</body>
</html>

Then I open the page via localhost/that-page.php and refresh ..

Cookie Test

You have a cookie!

In my test environment, setcookie() works normally without any warning. Is something wrong with my settings? Thank you.

Win7x64 and XAMPP 1.8.1 used

The only environmental issue that can lead to to this behavior is for output buffering to be turned on.

This can be done in a number of ways

In the php.ini with

 output_buffering = On

or

In htaccess/httpd.conf with

 php_flag output_buffering On

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM