Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I redirect in PHP without header errors?

How can I redirect in PHP with this setup below without getting header output errors, I understand that nothing can be printed to the browser before a header is set, I am looking for a solution, not an explanation of why it happens please.

<?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();
    }
}
?>

I would like to user php's header function and not a meta or javascript redirect

Also maintainning a list of pages that require login or not is not an option here if possible

like image 400
JasonDavis Avatar asked Aug 10 '09 15:08

JasonDavis


2 Answers

Use ob_start() in the first line even befor the include. so you can set headers anytime.

like image 95
Rufinus Avatar answered Oct 26 '22 23:10

Rufinus


Can't you just do this:

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

Or, put the include files in every one of the "SOME-FILE-HERE"-type files, if that's possible, so you end up with:

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

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

<?php
include ('footer.inc.php');
?>
like image 33
DisgruntledGoat Avatar answered Oct 27 '22 00:10

DisgruntledGoat