简体   繁体   中英

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. 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.

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. I read somewhere about ob_start() but I don't know if that's necessary...

mail() doesn't generate any output. You probably have some whitespace at the top of the file before the opening <?php tag.

Modifying the HTTP header with header requires that it has not been sent yet. 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 ).

The position where the output happened that caused sending the HTTP header is in the error message (“output started at file ‍:‍ line ”).

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.

If you for some reason want to have this make sure your php code still is above all that.

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”'

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