I need a fast and reliable way to map an absolute or relative local path (say ./images/Mafalda.jpg
) to it's corresponding absolute URL, so far I've managed to come up with this:
function Path($path)
{
if (file_exists($path) === true)
{
return rtrim(str_replace('\\', '/', realpath($path)), '/') . (is_dir($path) ? '/' : '');
}
return false;
}
function URL($path)
{
$path = Path($path);
if ($path !== false)
{
return str_replace($_SERVER['DOCUMENT_ROOT'], getservbyport($_SERVER['SERVER_PORT'], 'tcp') . '://' . $_SERVER['HTTP_HOST'], $path);
}
return false;
}
URL('./images/Mafalda.jpg'); // http://domain.com/images/Mafalda.jpg
Seems to be working as expected, but since this is a critical feature to my app I want to ask if anyone can spot any problem that I might have missed and optimizations are also welcome since I'm going to use this function several times per each request. Anyone?