Assume I have a form on index.php
and it points to test.php
which process the data submitted.
index.php
looks like the below:
<form action="test.php"></form>
It should cause an error if test.php
looks like the below:
( As you can see, there is already an output Nice
being sent before the header ()
)
echo 'Nice';
header ( "Location: https://example.com" );
But what if I put it inside a function and call the function?
echo 'Nice';
function process () {
header ( "Location: https://example.com" );
}
process ();
Would it works in this case since it’s inside a function, and would it cause an error?
3
Answers
As stated here:
https://www.php.net/manual/en/function.header.php
So the problem would arise only because you called it after echoing text to the response while you had to do it before.
Calling it inside a function doesn’t change that requirement, because the header is part of the response that you already sent echoing text.
It might be useful to understand why there is an error if you call
header()
at the wrong time.The response from your web server to a browser looks something like this, with a status, then "headers", then a "body":
When you call
header()
, you are asking the server to add a line next to theContent-Type
, before the "body". (And adding aLocation
header in particular also changes the status code in the very first line from200
to301
to indicate a redirect.) Roughly like this:If the server has already sent the first version, because you told it to output "Nice", there’s no way for it to "take it back" and send the second version. That’s just as true in your second code as in your first: you’re telling the server to output "Nice", and then telling it to go back and edit the headers, but it’s too late.
Short answer:
To:
The issue is that you are sending an output for the user to see "Nice!" before setting the redirect header. When you send Nice! The server is forced to send the packets with a Header already. You have to learn more about how HTTP protocol works.
The header is like the label on the envelop when you mail it via postal service. The content "Nice" is like the letter inside the envelope. You are trying to send a letter to your friend and then change the label address after it arrives.
Instead for that kind of functionality what you could do is use HTML or Javascript to make the redirect. (HTML way is an obsolete way) so I gave you the Javascript. However this is not good way of writing code but it works and I do it all the time.
Since you seem to like to output things after redirecting user you might want to buffer your output or simply give some time for the redirect to process:
It’s so refreshing to see a year 2000 style of coding and redirects. 🙂
Cheers! Very Nice!!!