[英]Seeing “Cannot modify header information” error when attempting to redirect
I have a basic PHP mail()
script which e-mails users the details of a form they've just submitted. 我有一个基本的PHP
mail()
脚本,该脚本通过电子邮件向用户发送他们刚刚提交的表单的详细信息。 The PHP inserts all the data into the database fine, but there's a problem when I want to redirect them after the data has finished processing. PHP可以将所有数据很好地插入数据库中,但是当我想在数据处理完成后重定向它们时会出现问题。
I'm currently using: 我目前正在使用:
mail($email, $subject, $message, $headers);
header('Location: '/reservations/?res='.$res.'&id='.$id.'');
But it's throwing up this error: 但这引发了此错误:
Warning: Cannot modify header information - headers already sent
I realise you can't send multiple headers, but is there any way of differentiating between the mail and location headers? 我知道您不能发送多个标头,但是有什么方法可以区分邮件标头和位置标头? I don't want to use JavaScript redirect because it's too slow and lags.
我不想使用JavaScript重定向,因为它太慢且滞后。 I read somewhere about
ob_start()
but I don't know if that's necessary... 我在某处读到有关
ob_start()
但我不知道这是否有必要...
mail() doesn't generate any output. mail()不会产生任何输出。 You probably have some whitespace at the top of the file before the opening
<?php
tag. 在打开
<?php
标记之前,您可能在文件顶部有一些空格。
Modifying the HTTP header with header
requires that it has not been sent yet. 使用
header
修改HTTP标header
要求尚未发送它。 And that happens when the first output happened. 当第一个输出发生时,就会发生这种情况。
So to avoid the HTTP header being sent you need to avoid any output before calling header
or you need to buffer it so that it doesn't get sent (see output control , especially ob_start
). 因此,要避免发送HTTP标头,您需要在调用
header
之前避免任何输出,或者需要对它进行缓冲以使它不会被发送(请参见输出控件 ,尤其是ob_start
)。
The position where the output happened that caused sending the HTTP header is in the error message (“output started at file : line ”). 引起发送所述HTTP标头,其中所述输出发生的位置是在错误消息(“输出开始的文件 : 线 ”)。
Add the "@" symbol before the mail function, it will be solve your problem. 在邮件功能之前添加“ @”符号,它将解决您的问题。
ie., 即
@mail($email, $subject, $message, $headers);
header('Location: /reservations/?res='.$res.'&id='.$id);
<?php
mail($email, $subject, $message, $headers);
header('Location: '/reservations/?res='.$res.'&id='.$id.'');
?>
Should work just fine. 应该工作正常。 Just make sure you have nothing else happening before this.
只要确保您在此之前没有其他事情发生即可。 In other words, do not have a
<body>
, <title>
, <head>
or anything above your code. 换句话说,没有
<body>
, <title>
, <head>
或代码上方的任何内容。
If you for some reason want to have this make sure your php code still is above all that. 如果您出于某种原因想要这样做,请确保您的php代码仍然高于一切。
Exampel: 示例:
<?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>
您好,更好的选择是您可以使用javascript window.location返回页面,例如echo'window.location =“ / reservations /?res = $ res&id = $ id”'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.