未设置饼干


Cookie not being set

你能帮帮我吗?我的网站没有设置以下简单的cookie。虽然其他一些登录脚本可以,但这个不起作用。谢谢

测试.php

...
<form action="test2.php" method="post">
        Email: <br />
        <input type="email" name="email" value=""/> <br />
        <input type="submit" name="submit" value="Next"/> 
</form>
...

测试2.php

<?php ob_start(); ?>
<?php
// call the header of the page
require('header.html');
// connect to database
require "connect.php";
?>
<?php
    $email = $_POST['email'];
    // set cookie
    $one_hour = time() + 3600;
    $set = setcookie(user_email, $email, $one_hour);
    if($set == TRUE) {
        print '<p> Cookie set</p>';
    } else {
        print '<p> Cookie not set</p>';
    }
// call footer of the page
require('footer.html');
?>
<?php ob_flush(); ?>

运行上述脚本后,我收到此错误:

警告:无法修改标头信息 - 标头已由/websites/public_html/test2.php:1 中的/websites/public_html/test2.php 第 16 行发送

未设置饼干

  • PS:我的脚本上的第 16 行是"$set = setcookie(email_noaccount, $email, $hr(;">

只需按照以下方式更改上面的代码并尝试,将 ob_start(( 放在 require(( 之后

<?php
require "connect.php";
require('header.html');
?>
<?php ob_start(); ?>

在需要执行以下操作之前,您将内容发送到输出缓冲区:

<?php ob_start(); ?>
  <--- right here
<?php
// call the header of the page
require('header.html');
// connect to database
require "connect.php";
?>
  <--- and right here
<?php
    $email = $_POST['email'];

您应该删除输出中不必要的空格,以便在构建输出之前执行服务器端处理(包括标头修改(。

理想情况下,您不想将两者混合使用。 服务器端处理应在生成输出之前进行,然后使用处理结果生成输出并将其发送到客户端。