PHP Redirect
Redirects are performed by sending the relevant HTTP status code in combination with a Locatin header, which indicates the end location of the redirect.
Edited: 2019-09-11 16:05
The PHP Redirect performed by sending the HTTP Location Header to the browser, which can be done with the PHP Header function. The location should be sent a long with the relevant HTTP status message – the type of redirect is controlled trough a separate header sent by PHP. Its important to get both the location header, and the status message right.
The below example deals with a 301 Permanent Redirect – permanent redirection is performed for pages that have moved, this is done so that search engines will automatically recognize them as having been moved.
if ($_SERVER['REQUEST_URI'] === '/my-old-page.php') {
header("HTTP/1.1 301 Moved Permanently");
header('Location: http://beamtic.com/');
exit();
}
The $_SERVER['REQUEST_URI'] variable may not be the best way to perform your redirects, but it does give you a basic idea about how you can perform easily perform redirects.
The exit function placed on the last line, makes sure that any code coming afterwards, will not be run – you can combine this with a if statement to check if the page has been moved.
Redirecting Multiple Pages
The above example is not very suitable if you got a lot of pages that needs to be redirected – one way to redirect multiple pages, is to list them in an array first, and then loop trough this array.
Arrays can be constructed easily, one of the easiest ways is to do like below.
$OldPages[1] = 'Old-Page-1.php';
$OldPages[2] = 'Old-Page-2.php';
$OldPages[3] = 'Old-Page-3.php';
// etc...
You would then create an array containing all the new locations.
$NewPages[1] = 'http://beamtic.com/New-Page-1';
$NewPages[2] = 'http://beamtic.com/New-Page-2';
$NewPages[3] = 'http://beamtic.com/New-Page-3';
// etc...
These can then be checked for in our loop – the full code for this example, is provided below.
// Old Locations
$OldPages[1] = 'Old-Page-1.php';
$OldPages[2] = 'Old-Page-2.php';
$OldPages[3] = 'Old-Page-3.php';
// New Locations Below!
$NewPages[1] = 'http://beamtic.com/New-Page-1';
$NewPages[2] = 'http://beamtic.com/New-Page-2';
$NewPages[3] = 'http://beamtic.com/New-Page-3';
$MaxPages = count($OldPages);
$Counter = 1;
while ($Counter <= $MaxPages) {
if ($_SERVER['REQUEST_URI'] === $OldPages["$Counter"]) {
header("HTTP/1.1 301 Moved Permanently");
header('Location: ' . $NewPages["$Counter"]);
exit();
}
++$Counter;
}
Tell us what you think: