PHP / XHTML. Should I place everything in echo tags?
A quick question involving PHP development, I seem to be wondering about this more and more as I develop more c开发者_高级运维omplex 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.
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
}
?>
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();
}
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.
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.
精彩评论