Free, tested & ready to use examples : PHP permanent redirect header 301 HTTP HTTPS location
AnyExample.com
 
Webanyexample.com
 

Redirect function with permanent 301 redirect support

abstract 
Here is an example of simple function ae_redir() for HTTP redirect. It supports relative site paths and permanent(seo-compatible) redirects. There is also function ae_redir_die() which stops execution of script after sending redirect.
compatible 
  • PHP 4.1.0 or higher
  • PHP 5

ae_redir function uses two arguments:

  • distination URL or relative path
  • optional argument — boolean flag for sending 301 permanent redirect
    301 permanent redirect is used by search engines (like Google) to associate different URLs with the same page(and pagerank)

source code: php
<?php 
function ae_redir($uri, $isperm=false)
{
    if (
$isperm)
        
header("HTTP/1.1 301 Moved Permanently");

    if ((
substr($uri, 0, 5) != 'http:') &&
        (
substr($uri, 0, 6) != 'https:'))
        
header("Location: http://".$_SERVER['HTTP_HOST'].$uri);
    else
        
header("Location: {$uri}");
}

function
ae_redir_die($url, $isperm=false)
{
ae_redir($url, $isperm); exit(); }

?>

Usage example:

source code: php
<?php 

// Example 1:
ae_redir("http://www.apple.com");
// Redirect to www.apple.com and continue executing code

...

// Example 2:
ae_redir("https://www.gmail.com");
// HTTPS redirects are also supported

...     

// Example 2:     
ae_redir("http://www.microsoft.com", true);
// Send permanent redirect to www.anyexample.com
// For example, you could register www.microsoft-another-domain.com
// and put this code to index.php to tell search engines
// that www.microsoft-another-domain.com is just another domain for
// microsoft.com

...

// Example 3:
ae_redir_die("http://www.anyexample.com");
// Redirect to www.anyexample.com and stop executing

...

// Example 4:
ae_redir_die("/error.php?msg=error");
// Redirect to yoursite.url/error.php?msg=error and end program

?>
warning 
  • Most of the time you should use ae_redir_die() function to avoid execution of superfluous code.
tested by AnyExample.com on 2007-05-30
  • FreeBSD 6.2 :: PHP 5.2.1
  • RHEL 5.0 :: PHP 4.4.5
 


 
© AnyExample 2007
License | Privacy | Contact