Difference in true and false in header('Location: ') function in PHP

Asked

Viewed 85 times

2

I was reading some articles about page redirection with the header() function, and came across two examples to use the function:
1)

<?php     
header('Location: endereço', **true**, 301);  
exit();  
?>  

2)

<?php     
header('Status: 301 Moved Permanently', **false**, 301);  
header('Location: endereço');  
exit();  
?>  

I tested both examples and they both worked, but I couldn’t find an explanation of the difference from false to true after "[...]address',". Could someone help me?

1 answer

4

The true and false, that is changing, is the Replace, according to the documentation:

header ( string $header [, bool $replace = TRUE [, int $http_response_code ]] ) : void

What matters to us is the definition of $replace:

Replace: The optional replace Parameter indicates whether the header should replace a Previous similar header, or add a Second header of the same type. By default it will replace, but if you pass in FALSE as the Second argument you can force Multiple headers of the same type.


When he’s true (and is the default value) it will replace the header, while if it is as false the value will not be replaced, for example:

header('Location: https://google.com');
header('Location: https://bing.com');

This should result in only a single header Location: https://bing.com, that’s because the https://bing.com replaces the https://google.com. In the meantime, if you’re like false:

header('Location: https://google.com', false);
header('Location: https://bing.com', false);

This should present the two headers, not just the last one. That’s because the false will not replace.


Meanwhile, the Location cannot appear multiple times in the same header. At least, in RFC 7230:

A Sender MUST NOT generate Multiple header Fields with the same field name in a message unless either the entire field value for that header field is defined as a comma-separated list [i.e., #(values)] or the header field is a well-known Exception (as noted Below).

The Location no such exceptions and cannot display lists. Already the Set-Cookies is an exception, for example. The WWW-Authenticate is a list, so it can also be divided between several individual headers. Considering the Set-Cookies, because it is common, in the same request can receive several Set-Cookies in the same header. So this would be a scenario where you would use the false in the header(), because if you use the true (standard) only one Set-Cookie would exist.


Browser other questions tagged

You are not signed in. Login or sign up in order to post.