lime icon

Phosphorus and Lime

A Developer's Broadsheet

This blog has been deprecated. Please visit my new blog at klenwell.com/press.
PHP: get_absolute_url() [NOTE: flawed]
Note: this does not work for reasons my brain is too addled to explain right now. See this function:

Slow day at work, so I just rewrote my function get_path_url so that it now safely returns paths that are already absolute urls:

/* get_absolute_url
*************************************************/
function get_absolute_url($path = 'default')
{
// *** DATA

// internal vars
$_slash = '/';
$_url_root = "http://".$_SERVER['HTTP_HOST'];
$_host = '';
$_protocol = 'http';
$_port = 80;
$_realpath = '';
$_root = '';
$_url_tail = '';

// return value
$_abs_url = '';


// *** MANIPULATE

// set default path
if ( $path == 'default' )
{
$path = $_SERVER['SCRIPT_FILENAME'];
}

// path is url
if ( preg_match('%^(http)s?://%i', $path) )
{
return $path;
}

// get url root

# get host
if ( !empty($_SERVER['HTTP_HOST']) )
{
list($_host) = explode(':', $_SERVER['HTTP_HOST']);
}
elseif (!empty($_SERVER['SERVER_NAME']))
{
list($_host) = explode(':', $_SERVER['SERVER_NAME']);
}

# protocol
if ( isset($_SERVER['HTTPS']) && !strcasecmp($_SERVER['HTTPS'], 'on') )
{
$_protocol = 'https';
}

# port
if ( isset($_SERVER['SERVER_PORT']) )
{
$_port = $_SERVER['SERVER_PORT'];
}

if ( ($_protocol == 'http' && $_port == 80) || ($_protocol == 'https' && $_port == 443) )
{
unset($_port);
}

# build url root
$_url_root = $_protocol .'://'. $_host . (isset($_port) ? ':'. $_port : '');


// get realpaths

# path
$_realpath = realpath($path);
trigger_notice($_realpath);

# root
$_root = realpath($_SERVER['DOCUMENT_ROOT']) . $_slash;

# add slash back to directories (realpath() trims last slash)
if ( is_dir($path) )
{
$_realpath = $_realpath . $_slash;
}

// normalize paths
$_realpath = trim(str_replace("\\", $_slash, $_realpath));
$_root = trim(str_replace("\\", $_slash, $_root));

// is root in path? (will return 0, so use identical operator (===, !==)
if ( strpos($_realpath, $_root) !== FALSE )
{
# subtract root from path
$_url_tail = str_replace( $_root, '', $_realpath );
$_abs_url = $_url_root . $_slash . $_url_tail;
}
// relative path
elseif ( strlen($_realpath) )
{
$_abs_url = $_url_root . $_slash . $_realpath;
}
else
{
trigger_error("path [$path] url could not be determined", E_USER_WARNING);
$_abs_url = FALSE;
}

// *** RETURN

return $_abs_url;

} # end Fx
/*______________________________________________*/


Note: I was having issues using realpath() -- something to do with realpath() on shared Windows servers. It did work with this realpath alternative in its place, however.

Credit goes out to the open scripts out there I consulted in creating this one. Curiously, the PEAR HTTP:absoluteURI() did not successfully do this for me. Perhaps I wasn't using it as intended. But it did help me figure out how to build the url head.

keywords: php, url, path, absolute