如何在没有标题错误的情况下在PHP中重定向?

Jas*_*vis 5 php redirect header

如何使用下面的设置在PHP中重定向而不会出现标题输出错误,我知道在设置标题之前没有任何内容可以打印到浏览器,我正在寻找解决方案,而不是解释为什么会发生这种情况.

<?PHP
// include header
include ('header.inc.php');



// In my body section file if this is a page that requires a user be logged in then
// I run a function validlogin($url-of-page-we-are-on); inside of that file
//the function is below, it outputs a redirect to login page if not logged in

// include body of page we want
include ('SOME-FILE-HERE.php');



// include footer
include ('footer.inc.php');



// here is the function that is in the body pages, it is only called on a page that we require a logged in user so there are hundreds of pages that do have this and a bunch that don't, it's on a page to page basis
function validlogin($url) {
    if ($_SESSION['auto_id'] == '') {
        $msg = 'Please login';
        $_SESSION['sess_login_msg'] = $msg;
        $_SESSION['backurl'] = $url;
        $temp = '';
        header("Location: /");
        exit();
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

我想用php的头函数而不是元或javascript重定向

如果可能的话,还可以在此处维护需要登录的页面列表

Ruf*_*nus 10

在第一行中使用ob_start()甚至是include.所以你可以随时设置标题.


Dis*_*oat 2

你不能这样做吗:

<?php
validlogin($url); // call the function here
include ('header.inc.php');
include ('SOME-FILE-HERE.php');
include ('footer.inc.php');
?>
Run Code Online (Sandbox Code Playgroud)

或者,如果可能的话,将包含文件放入每个“SOME-FILE-HERE”类型文件中,这样您最终会得到:

<?php
validlogin($url); // call the function here
include ('header.inc.php');
?>

<h1>Page heading</h1>
...page content etc...

<?php
include ('footer.inc.php');
?>
Run Code Online (Sandbox Code Playgroud)