Redirection

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Redirection

Post by timvw »

The following script redirects to $location.

If $location is not an absolute URI it will generate an absolute URL.
When appropriate, the session_id will be appended.

Code: Select all

<?php
function redirect($location)
{
  $url = '';
  
  // parse of the location into URL
  $parts = parse_url($location);
  
  // lookup scheme
  if (!isset($parts['scheme']))
  {
    // choose between HTTP and HTTPS as scheme
    $parts['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
  }
  $parts['scheme'] = strtolower($parts['scheme']);
  
  // lookup host
  if (!isset($parts['host']))
  {
    $parts['host'] = $_SERVER['SERVER_NAME'];

    // lookup port
    if (!isset($parts['port']))
    {
      $ports = array('https' => 443, 'http' => 80);
      if (!isset($ports[$parts['scheme']]) || $ports[$parts['scheme']] != $_SERVER['SERVER_PORT'])
      {
        $parts['port'] = $_SERVER['SERVER_PORT'];
      }
    }
  }

  // lookup path
  if ($parts['path']{0} != '/')
  {
    $path = str_replace('\\', '/', dirname($_SERVER['PHP_SELF']));
    $path .= '/';
    $parts['path'] = $path . $parts['path'];
  }

  // add eventual session_id
  if (!isset($_COOKIE[session_name()]) && isset($_SESSION))
  {
    // hosts needs to be the same
    if ($parts['host'] == $_SERVER['SERVER_NAME'])
    {
      // http://host is different than https://host
      if (($parts['scheme'] == 'https' && !empty($_SERVER['HTTPS'])) || ($parts['scheme'] == 'http' && empty($_SERVER['HTTPS'])))
      {
        if (!isset($parts['query']))
        {
          $parts['query'] = session_name() . '=' . session_id();
        }
        // if there is already a session_id, don't override
        else
        {
          $pos = strpos($parts['query'], session_name() . '=');
          if ($pos === false)
          {
            $parts['query'] .= '&' . session_name() . '=' . session_id();
          }
        }
      }
    }
  }
  
  // rebuild URL
  $url = $parts['scheme'];
  $url .= '://';
  if (isset($parts['user']))
  {
    $url .= $parts['user'];
    if (isset($parts['pass']))
    {
      $url .= ':' . $parts['pass'];
    }
    $url .= '@';
  }
  $url .= $parts['host'];
  if (isset($parts['port']))
  {
    $url .= ':' . $parts['port'];
  }
  $url .= $parts['path'];
  if (isset($parts['query']))
  {
    $url .= '?' . $parts['query'];
  }
  if (isset($parts['fragment']))
  {
    $url .= '#' . $parts['fragment'];
  }
  
  //echo $url . '<br>';
  header('Location: ' . $url);
  exit;
}
?>
Post Reply