I am quite new to php, I did some research and tried someone else’s solution but it did not work out for me. I want to redirect users to another page after a certain code has been executed. I realized that there are no error messages and the site does not change. So I removed almost everything from the code and put it into a small test.php file.
The same issue persists.
<!DOCTYPE html>
<html>
<body>
<h1>Tes2</h1>
<?php
// Execute some code here
sleep(10); // Give the user 10 seconds to read the output of my code
// redirect the user with php or trigger a JS script to do that
header("Window-target: _parent");
header("Location: https://www.w3schools.com/");
?>
</body>
</html>
Expectation: The page should execute the main php script (visualized by the comment) and trigger a timer. When the timer ends, it should redirect me to "www.w3schools.com". There should be no errors or other messages. The redirect should be done by the php code, if possible (JS would be a possible way to solve this, but I would still need to start the JS code after my php code has been executed).
Result: The page shows up and loads the of the html code. The site remains and does not change. There are no errors.
Environment: Running on Chromium
Version 96.0.4664.45 (Offizieller Build) for Linux Mint (64-Bit)
The Website is functional and did execute PHP code as expected, but not this one.
Is there a light weight and universal (for most popular browsers) solution which will redirect the users to another page?
2
Answers
A combination of PHP and JS seems to be the easiest solution. But that might be only my opinion. I tried to document the code as good as possible, so others can understand it:
Headers must be set before any data is transmitted, so you can’t just stick them in the middle of a file. Quoting the the manual:
So at the very least you’ll need to rewrite your file to:
Also, never
sleep()
in an http(s) response: that response should finish as fast as it can, no matter what content it needs to generate. Sleep has no place in (really any) PHP code.