For a server-side redirect, send the Location header before any response body and stop execution immediately after the redirect. JavaScript and meta-refresh redirects are usually fallbacks, not the primary PHP approach.
<?php
header('Location: /new-page.php', true, 302);
exit;
| HTTP Status Code | Temporary / Permanent | Cacheable | Request Method Subsequent Request |
| 301 | Permanent | yes | GET / POST may change |
| 302 | Temporary | not by default | GET / POST may change |
| 303 | Temporary | never | always GET |
| 307 | Temporary | not by default | may not change |
| 308 | Permanent | by default | may not change |
header ("Location: https://www.starjokes.com");
/* Redirect browser to starjokes.com web site */
exit; // Closes further script execution
You can see this code above will redirect the page to a new url.
header("HTTP/1.1 301 Moved Permanently");
header ("Location: https://www.allkm.com/km-basics/data.php");
exit;
If we send any html tag or any other data to the browser before the redirection command, then we will get an error message like this
<b>Warningb>: Cannot modify header information -
headers already sent by (output started at L:\php_files\t\test6.php:13) in L:\php_files\t\test6.php on line 14
if (!headers_sent()) {
// No header sent , so you can use PHP to redirect //
header("HTTP/1.1 301 Moved Permanently");
header ("Location: mynewpage1.html");
exit;
}else{
// Header already sent, so use JavaScript to redirect //
print "<script>";
print " self.location='mynewpage2.html';";
print "</script>";
}
By using JavaScript also the redirection can be done. Here is the code printing the javascript code for the browser to redirect. But this will work if JavaScript is enabled in the browser.
print "<script>";<br>print " self.location='mynewpage.html';";
print "</script>";
You can read about Meta Redirect here
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.