Tessmore
Tessmore

Reputation: 1039

Using exit() and header() to redirect as a one-liner

My question is about writing the following as a one-liner:

header('Location: www.somesite.com');
exit(0);

PHP documentation says you can also write exit('some string'); and it will output that string. I figured the header() function just creates some raw HTTP header and this should be a string of text right? So the equivalent of the above two lines could be:

exit(header('Location: www.somesite.com'));

I tested it a bit and it works (i.e exits properly and redirects.. havn't seen any shennenigans going on yet).

However,I cannot find anything about this on google and I am not 100% sure the header() creates an actual string that the exit() function expects.

So is it a cool trick or wrong use of PHP functions and if wrong, why?

Upvotes: 2

Views: 265

Answers (2)

xdazz
xdazz

Reputation: 160883

Even through you could do that, but two line code is more readable and clean.

header('Location: www.somesite.com');
exit(0);

If you want one line, you could make a function.

function redirect($url) {
    header("Location: $url");
    exit(0);
}

Upvotes: 1

raidenace
raidenace

Reputation: 12836

header() does not return anything to the exit() function - it sends out raw http headers and has a return type of void. The exit() function does not require a mandatory parameter, so yeah I think what you do would work :)

Upvotes: 2

Related Questions