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?
>Solution :
Short answer:
header ( "Location: https://example.com" );
To:
echo "<script> window.location.href='https://example.com </script>" ;
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:
<?php
echo 'Nice';
?> <!--NOTICE I CLOSED PHP TAG -->
setTimeout(function() {
window.location.href = ‘https://example.com/’;
},5000);
Please wait while we redirect you in 5 seconds or simply <a href="https://example.com">click here.<a>
<?php
echo "I like to write PHP code";
?>
It’s so refreshing to see a year 2000 style of coding and redirects. 🙂
Cheers! Very Nice!!!