tags:

views:

81

answers:

4

A quick question involving PHP development, I seem to be wondering about this more and more as I develop more complex sites. Basically say we have a basic PHP / XHTML inbox (messaging system). I perform checks at the top (check if user is logged in, check if user has correct permissions etc). Then use the 'header('location:www.abc.com)' function if the authentication fails. The question is do I write the rest of the inbox code in a huge 'else' block or just use standard html. I read somewhere about about it being bad to put any code after using the 'header' function.

+4  A: 

Just follow your header with

exit();

Than it won't be a problem.

see third example here

Also you don't need a big echo like that, you can echo html like this aswell if you want:

<?php
  //php stuff
  if(test){
?>

   html here

<?php
  }
  else{
?>

   other html

<?php
  }
?>
red-X
Ahh that's a neat trick. Thanks
st3
Even better, if the HTML code is long, use include() and put the html code in two different files.
Palantir
I find if youre swtiching in and out of php and htm in control blocks its better to use the alternate syntax like: `<?php if(condition): ?> html <?php else: ?> html <?php endif; ?>`
prodigitalson
+1  A: 

The reason you read it's bad, is that clients don't have to honor the Location: abc header - so if you keep sending them data they might just show it, perhaps making it possible to snoop on your users data.

What you can do, is after you send the Location: abc header, you simply exit the script, like this:

if(!$user->is_authenticated()) {
    header("Location: abc");
    exit();
}
gnud
ah! the exit() function, thanks everyone, that's brilliant.
st3
+1  A: 

After the header redirection, you put a fat "return" or "exit", so your script terminates there, then you close the if. Then you can happily code as you would normally.

It's not true that you should not put anything after a header() call. You should however remember that if you output anything before a header call, the script will fail. There are headers which require you to code on, like the Content-type header. After a redirection header, however you should always put an exit() call, in case the browser doesn't obey the instruction.

Palantir
+1  A: 

I read somewhere about about it being bad to put any code after using the 'header' function.

That's not entirely true, because it's not permitted to send output (HTML or raw output) to the browser, before you send out a header. When you DO send output before you send a header, you'll get a 'Header already sent' error.

After a header function, the rest wont be executed, so a return or exit is not required.

For the question if you need to put everything in an if/else structure: This is also not required, the only thing you have to do is a basic check if some's logged in and if not, you'll perform a redirect using the header function. No need for an extensive if/else structure.

GaMer13