rez
rez

Reputation: 95

PHP: Systems path to actual URL

Before i make my question I wanna say that I have tried every related post I found from stackoverflow such as PHP - Convert File system path to URL and nothing worked for me, meaning I did not get the Url I was looking for.

I need a

function PathToUrl($path) 
{
 ... 
}  

which returns the actual Url of the $path

Example usage: echo PathToUrl('../songs'); should output http://www.mywebsite.com/files/morefiles/songs.

Note: The problem with the functions i found on stackoverflow is that they dont work with path that contains ../ for example on echo PathToUrl('../songs'); i would get something similar to http://www.mywebsite.com/files/morefiles/../songs which is not what i am looking for.

Upvotes: 1

Views: 158

Answers (2)

Kraang Prime
Kraang Prime

Reputation: 10479

I see an answer was already posted, however I will post my solution which allows for direct specification of the URL :

echo up('http://www.google.ca/mypage/losethisfolder/',1);

function up($url, $howmany=1) {
    $p = explode('/', rtrim($url, '/'));
    if($howmany < count($p)) {
        $popoff = 0;
        while($popoff < $howmany) {
            array_pop($p);
            $popoff++;
        }
    }
    return rtrim(implode('/', $p), '/') . '/';
}

Following is a much more elegant solution for virtual paths :

$path = '/foo/../../bar/../something/../results/in/skipthis/../this/';

echo virtualpath($path);

function virtualpath($path = null) {
    $loopcount = 0;
    $vpath = $path;
    if(is_null($vpath)) { $vpath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); }
    $vpath = rtrim($vpath,'/') . '/';
    while(strpos($vpath,'../') !== false ) {
        if(substr($vpath,0,4) == '/../') { $vpath = '/'. substr($vpath,4); }
        $vpath = preg_replace('/(\/[\w\d\s\ \-\.]+?\/\.\.\/)/', '/', $vpath );
    }
    return $vpath;
}

Upvotes: 1

Adam Sinclair
Adam Sinclair

Reputation: 1649

Here you go, I made this function and it works perfectly:

function getPath($path)
{
    $url = "http".(!empty($_SERVER['HTTPS'])?"s":"").
        "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    $dirs = explode('/', trim(preg_replace('/\/+/', '/', $path), '/'));
    foreach ($dirs as $key => $value)
        if (empty($value))  unset($dirs[$key]);
    $parsedUrl = parse_url($url);
    $pathUrl = explode('/', trim($parsedUrl['path'], '/'));
    foreach ($pathUrl as $key => $value)
        if (empty($value))  unset($pathUrl[$key]);
    $count = count($pathUrl);
    foreach ($dirs as $key => $dir)
        if ($dir === '..')
            if ($count > 0)
                array_pop($pathUrl);
            else
                throw new Exception('Wrong Path');
        else if ($dir !== '.')
            if (preg_match('/^(\w|\d|\.| |_|-)+$/', $dir)) {
                $pathUrl[] = $dir;
                ++$count;
            }
            else
                throw new Exception('Not Allowed Char');
    return $parsedUrl['scheme'].'://'.$parsedUrl['host'].'/'.implode('/', $pathUrl);
}

Example:

Let's say your current location is http://www.mywebsite.com/files/morefiles/movies,


echo getPath('../songs');

OUTPUT

http://www.mywebsite.com/files/morefiles/songs

echo getPath('./songs/whatever');

OUTPUT

http://www.mywebsite.com/files/morefiles/movies/songs/whatever

echo getPath('../../../../../../');

In this case it will throw an exception.


NOTE

I use this regex '/^(\w|\d|\.| |_|-)+$/' to check the path directories which mean that only digit, word characters, '.', '-', '_' and ' ' are allowed. An exception will be trown for others characters.

The path .///path will be corrected by this function.

USEFUL

Upvotes: 2

Related Questions