I want to send my users to different pages based on user action. So I made multiple functions at the top of the page like so:
<?php
function one() {
header("location: pagea.php");
}
function two() {
header("location: pageb.php");
}
function three() {
header("location: pagec.php");
}
?>
Of course I get an error because I am re declaring headers. At first I though it was going to be okay since I am containing them inside functions and am calling any one function at a time. But still I get the error. Is there any other way of doing this?
The header() function in PHP sends a raw HTTP header to a client or browser. Before HTML, XML, JSON, or other output is given to a browser or client, the server sends raw data as header information with the request (particularly HTTP Request).
The Content-Type header is used to indicate the media type of the resource. The media type is a string sent along with the file indicating the format of the file. For example, for image file its media type will be like image/png or image/jpg, etc. In response, it tells about the type of returned content, to the client.
One is header which starts with string “HTTP/” used to figure out the HTTP status code to send. Another one is the “Location” which is mandatory. replace: It is optional which indicates whether the header should add a second header or replace previous.
I think you misunderstand what the HTTP header Location
does.
The Location
header instructs the client to navigate to another page. You cannot send more the one Location
header per page.
Also, PHP sends headers right before the first output. Once you output, you cannot specify any more headers (unless you are using Output Buffering).
If you specify the same header twice, by default, header()
will replace the previous value with the latest one... For example:
<?php
header('Location: a.php');
header('Location: b.php');
header('Location: c.php');
will redirect the user to c.php
, never once passing by a.php
or b.php
. You can override this behavior by passing a false
value to the second parameter (called $replace
):
<?php
header('X-Powered-By: MyFrameWork', false);
header('X-Powered-By: MyFrameWork Plugin', false);
The Location
header can only be specified once. Sending multiple Location
header will not redirect the users to the pages... It will probably confuse the crap out of the UA. Also, understand that the code continues to execute after sending a Location
header. So follow that call to header()
with an exit
. Here is a proper redirect function:
function redirect($page) {
header('Location: ' . $page);
exit;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With