简体   繁体   English

PHP 5.4.X能够在HTML标记后放置setcookie()而不发出“标题已发送”警告吗?

[英]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. 我曾经遇到过警告:无法添加标头信息-尝试在echo或任何HTML标记后放置header() session_start()setcookie()已经发送的 header() 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. 但是,当我将本地服务器中的PHP升级到5.4.7 (在XAMPP 1.8.1中 )时,不再遇到此警告。 Is this normal for PHP 5.4.X? PHP 5.4.X正常吗?

I tried placing setcookie() after some texts and an echo in this example: 在此示例中,我尝试将setcookie()放在一些文本和echo之后:

<!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 .. 然后我通过localhost / that-page.php打开页面并刷新..

Cookie Test Cookie测试

You have a cookie! 你有饼干!

In my test environment, setcookie() works normally without any warning. 在我的测试环境中, setcookie()可以正常工作而不会发出任何警告。 Is something wrong with my settings? 我的设置有问题吗? Thank you. 谢谢。

Win7x64 and XAMPP 1.8.1 used 使用Win7x64XAMPP 1.8.1

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 在php.ini中

 output_buffering = On

or 要么

In htaccess/httpd.conf with 在htaccess / httpd.conf中

 php_flag output_buffering On

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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