Absolute vs Relative Path

implement full support for relative path

1. Objectives

  1. add support for relative path
  2. option to set only absolute path, enforce canonical URL
  3. option to auto set relative path/absolute URL
    • always adjusts to current environment
      • to run under multiple domains

Patches

  1. added option to switch between absolute and relative links
  2. set canonical context for feeds

impediments

  • parse_url & unicode

absolute path must ensured for

  1. cookiesURL
  2. redirect
  3. canonical
  4. sitemap
  5. XML feeds
  6. email content

Types Example
absolute URL https://example.com/folder/image.png
protocol-relative URL //example.com/folder/image.png
root-relative URL /folder/image.png
base-relative URL folder/image.png

2. Config

If canonical is not enforced, base_path is applied where possible, all other cases use always base_url.

  • base_url (absolute)
  • base_path (relative)
  • base_path (canonical ? base_url : base_path)

<?php

'base_url' => ($_SERVER['SERVER_PORT'] == 443
                ? 'https'
                : 'http'
            ) . '://' .
            $_SERVER['SERVER_NAME'] .
            (!in_array($_SERVER['SERVER_PORT'], [80, 443])
                ? ':' . $_SERVER['SERVER_PORT']
                : ''
            ) .
            (($path = preg_replace('/\/\//', '\/', trim(strtr(dirname($_SERVER['SCRIPT_NAME']), '\\', '/'), '/')))
                ? '/' . $path
                : ''
            ) . '/' ,

2.1. Get base URL

<?php

// returns the full absolute or relative URL to the directory where WackoWiki is installed
function get_base_url($absolute = null)
{
    $base_url = ($_SERVER['SERVER_PORT'] == 443
            ? 'https'
            : 'http'
        ) . '://' .
        $_SERVER['SERVER_NAME'] .
        (!in_array($_SERVER['SERVER_PORT'], [80, 443])
            ? ':' . $_SERVER['SERVER_PORT']
            : ''
        );
    $base_path = (($path = preg_replace('/\/\//', '\/', trim(strtr(dirname($_SERVER['SCRIPT_NAME']), '\\', '/'), '/')))
            ? '/' . $path
            : ''
        ) . '/';

    return ($absolute ? $base_url : '') . $base_path;
}

3. Relative URLs

<a href="/wiki/">

 'base_url' => '/wiki/',	

4. Absolute URLs

<a href="https://example.com/wiki/">

 'base_url' => 'http://example.com/wiki/',	

$base_url = 'http[s]://example.com/wiki/';
$base_path = '/wiki/';	

5. Canonical context

It sets canonical context for feeds, this solves three issues:

  • format($page['body_r'], 'post_wacko') -> renders content with canonical links
  • href() -> sets link absolute
  • link() -> sets path for global files absolute

6. Resources