Mapping Absolute / Relative (Local) Paths to Absolute URLs

Posted by Alix Axel on Stack Overflow See other posts from Stack Overflow or by Alix Axel
Published on 2010-05-02T02:29:58Z Indexed on 2010/05/02 2:37 UTC
Read the original article Hit count: 424

Filed under:
|
|
|
|

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.

© Stack Overflow or respective owner

Related posts about php

Related posts about url