lime icon

Phosphorus and Lime

A Developer's Broadsheet

This blog has been deprecated. Please visit my new blog at klenwell.com/press.
PHP: filepath_to_url()
A filepath_to_url function that should work, though I've only tested it on my local server. Uses my own function to normalize slashes, but not too hard to do within the function itself:

/* fx filepath_to_url
*************************************************/
function filepath_to_url($filepath)
{
// *** DATA

# internal
$_slash = '/';
$_url_rel = '';

# paths
$PATH = array();
$PATH['file'] = normalize_path($filepath, $_slash);
$PATH['www'] = 'http://' . $_SERVER['HTTP_HOST'] . $_slash;

# directory arrays
$_DIRS = array();
$_DIRS['filepath'] = explode($_slash, $PATH['file']);
$_DIRS['doc_root'] = explode($_slash, normalize_path($_SERVER['DOCUMENT_ROOT'],$_slash));
$_DIRS['diff'] = '';

# return
$url = '';

# DEBUG
#trigger_notice($filepath);
#trigger_notice($_DIRS);



// *** MANIPULATE

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

# compute path differences
$_DIRS['diff'] = array_values(array_diff($_DIRS['filepath'], $_DIRS['doc_root']));

# DEBUG
#trigger_notice($_DIRS);

# shift empty cells
if ( empty($_DIRS['diff'][0]) )
{
array_shift($_DIRS['diff']);
}

# get URL relative path
$_url_rel = implode('/', $_DIRS['diff']);

# build URL
$url = $PATH['www'] . $_url_rel;


// *** RETURN

return $url;

} # end Fx
/*______________________________________________*/


Successful on my local WAMP build and on my remote LAMP (actually, I think it is BSD) host.