Hi,

I've searched the internet about how to redirect users. I found the header function which is great.

I saw alot of this type of code


If (condition) {
 header ('Location: page.php');
}else {
header ('Location: otherpage.php');
}

yet, when i try it, it gives me an error (headers already sent). I then found out that the header function has to be the first line of code on the page. If that's so, how come people have the code above all over the page?

thank you

    Hi,

    the header line doesn't have to be the first line but there mustn't be any output (echo, empty lines in front of <?PHP and so on) in front of the header call.

      is there another way to redirect users? or a way to do the redirect like i stated above?

        basically would this make sense:

        if (!isset($_SESSION['username'])) {
        include ('yes.php');
        }else {
        include ('no.php');
        }
        

        thank you

          solved my inital problem.....

          put ob_start(); at the top...then i can put the header anywhere on my site and it'll work...

            Originally posted by grudz
            solved my inital problem.....

            put ob_start(); at the top...then i can put the header anywhere on my site and it'll work...

            That is of course the lazy (and expensive) way out. A bit more thought should see you rewriting your code so that you don't generate any output you don't need to (and why would you need to generate any output if you're just going to redirect them to a different page?) It's quite possibly just a matter of moving your original code up to where you shoved that ob_start() in (but that's just a guess supported only by a lack of evidence to the contrary).

              this page is not only a redirect page.....it'll check if the user is a member, if he is then show the restricted content, if he is not, then it redirects him....

                Originally posted by grudz
                ....it'll check if the user is a member, if he is then show the restricted content, if he is not, then it redirects him....
                [Emphasis mine]

                You pretty much said it right there: you've got no reason to generate any output at all until after you've done all your checks, and by then you'll know whether to redirect or not.

                Check out user's credentials.
                Are they a member?
                NO: send a redirect header, and exit this script.
                YES: Display restricted info
                  Write a Reply...