【问题标题】:Seeing "Cannot modify header information" error when attempting to redirect尝试重定向时看到“无法修改标头信息”错误
【发布时间】:2010-12-16 09:32:22
【问题描述】:

我有一个基本的 PHP mail() 脚本,它通过电子邮件向用户发送他们刚刚提交的表单的详细信息。 PHP 将所有数据插入到数据库中很好,但是当我想在数据处理完成后重定向它们时出现问题。

我目前正在使用:

mail($email, $subject, $message, $headers);

header('Location: '/reservations/?res='.$res.'&id='.$id.'');

但它抛出了这个错误:

Warning: Cannot modify header information - headers already sent

我知道您不能发送多个标头,但是有什么方法可以区分邮件标头和位置标头吗?我不想使用 JavaScript 重定向,因为它太慢而且滞后。我在某处读到过关于 ob_start() 的文章,但我不知道这是否有必要......

【问题讨论】:

    标签: php email header


    【解决方案1】:

    mail() 不会产生任何输出。在打开 <?php 标记之前,您可能在文件顶部有一些空格。

    【讨论】:

      【解决方案2】:

      使用header 修改HTTP 标头要求它尚未发送。当第一个输出发生时就会发生这种情况。

      因此,为了避免发送 HTTP 标头,您需要在调用 header 之前避免任何输出,或者您需要对其进行缓冲以使其不被发送(参见 output control,尤其是 ob_start)。

      导致发送 HTTP 标头的输出发生的位置在错误消息中(“output started at file‍:‍line”)。

      【讨论】:

        【解决方案3】:

        在邮件功能前添加“@”符号,即可解决您的问题。

        即,

        @mail($email, $subject, $message, $headers);
        header('Location: /reservations/?res='.$res.'&id='.$id);
        

        【讨论】:

        • 这只会抑制任何可能的错误消息。如果邮件有错误(我们不知道是否有),最好修复它。
        【解决方案4】:
        <?php
        mail($email, $subject, $message, $headers);
        header('Location: '/reservations/?res='.$res.'&id='.$id.'');
        ?>
        

        应该可以正常工作。只要确保在此之前没有发生任何其他事情。换句话说,不要在您的代码上方添加&lt;body&gt;&lt;title&gt;&lt;head&gt; 或任何内容。

        如果你出于某种原因想要这样做,请确保你的 php 代码仍然是最重要的。

        例子:

        <?php
        mail($email, $subject, $message, $headers);
        header('Location: '/reservations/?res='.$res.'&id='.$id.'');
        ?>
        <!DOCTYPE HTML>
        <html>
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Send mail</title>
        </head>
        
        <body>
        </body>
        </html> 
        

        【讨论】:

          【解决方案5】:

          你好更好的选择是你可以使用 javascript window.location 返回页面 喜欢 echo 'window.location="/reservations/?res=$res&id=$id"'

          【讨论】:

            猜你喜欢
            • 2014-03-07
            • 2018-05-22
            • 2023-03-14
            • 1970-01-01
            • 1970-01-01
            • 2010-12-27
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多