Andrey
Andrey

Reputation: 859

PHP header(); reliability

I need to redirect users if I don't want them to be able to access a certain page. How reliable is header('Location: ../acc/login.php'); for example? Can browsers ignore 302 errors, and is this the right way? Thanks in advance!

Upvotes: 2

Views: 1056

Answers (5)

hakre
hakre

Reputation: 197544

It depends a lot what you're trying to do. Technically spoken, header() is somewhat reliable. Only somewhat, because many PHP users have problems with it and to not get it to work.

PHP will prevent it from working if output has been already send to the browser. A drastic example:

<protected page content here>
<?php
    header('Location: login-first.php');
    exit();
?>

This would not work at all. You would eventually see even an error message with a warning.

Headers - by design - need to be send out before any other content (response body). They can not be send any longer if the response body has already started and PHP can't help you then in that case.

However, if you send headers before the response body, that function will work. Also the risk obviously to mess something up is not that drastic any longer, too:

<?php
    header('Location: login-first.php');
    exit();
?>
<protected page content here>

Upvotes: 4

JvdBerg
JvdBerg

Reputation: 21856

header is 100% reliable.

However header('Location: ../acc/login.php') will be evaluated in the browser to a real location on your website, and ../acc/login.php wil not form a url that is valid!

Upvotes: -1

xur17
xur17

Reputation: 516

I would send the header command and then the exit command "exit()" (to stop running the php code on the server) before displaying the rest of the page. This way the user would never be sent the page content even if they ignored the 302 redirection.

And yes the user can ignore the 302 redirection:

http://www.webmasterworld.com/html/3604591.htm

Upvotes: 0

Gung Foo
Gung Foo

Reputation: 13558

The browser can ignore header('Location: '); forwarding.

That is why you should always return after a call to a header() forward so the rest of your code does not execute should the browser not honor the forwarding.

It is the correct way to do things tho.

Upvotes: 0

Nikola K.
Nikola K.

Reputation: 7155

You can rely on header(), but make sure you called die(), exit() or return after that. Otherwise, script will continue its execution, which is potential security issue.

Upvotes: 4

Related Questions