Home > Net >  will header () works inside function after HTML
will header () works inside function after HTML

Time:11-16

I understand that there needs to be no output before header () even a space.

I have the below code to get the current URL:

$url = 'https://' . $_GET['SERVER_NAME'] . $_GET['REQUEST_URI']

If I use header ( "Location: $url" ) on the first line of the page, I think it might cause an infinity redirecting loop?

But what if I put it in a function and call it when a form is submitted like the below?

<form><input type="submit"></form>

<?php
$url = 'https://' . $_GET['SERVER_NAME'] . $_GET['REQUEST_URI']

function send () {
   header ( "Location: $url" );
}
?>

Note that the function is after the HTML but header () is in a function. Remember there needs to be no output before header (), so will this work, and does it cause an error?

Because if it's not in a function, assume it looks like this, for sure it gonna cause an error, right?

<form><input type="submit"></form>

<?php
$url = 'https://' . $_GET['SERVER_NAME'] . $_GET['REQUEST_URI']

header ( "Location: $url" );
?>

CodePudding user response:

This will fail, because the header() command does not run when you submit the form, even if you place it inside a JavaScript function.

PHP always runs on the server, not in the client. Everything it does happens before the client sees the response.

Header() must come first because it is a function like echo() that adds to the response that is sent to the client. Think of header ( "Location: $url" ); as being similar to echo "Header: Location: $url"; that just adds on to whatever else you have already written out for the page. (It isn't really an echo since it writes headers outside of the page body)

Note that you can have php code that does not generate output before a header() command. This is fine:

<?php
    $person = "Tad Person";
    $address = "100 Place Lane";
    if ($person == "Tad Person")
    {
        header('Location: tads_own_page.php');
        exit;
    }
    // else: the page for everyone except tad
    ....
  •  Tags:  
  • php
  • Related