Use PHP functions in JavaScript

JavaScript realpath

Return the resolved path

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
4041
42
43
44
4546
47
48
49
5051
52
53
54
55
function realpath (path) {
    // Return the resolved path  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/realpath    // +   original by: mk.keck
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: Returned path is an url like e.g. 'http://yourhost.tld/path/'
    // *     example 1: realpath('../.././_supporters/pj_test_supportfile_1.htm');
    // *     returns 1: 'file:/home/kevin/workspace/_supporters/pj_test_supportfile_1.htm'    
    var p = 0, arr = [];
    /* Save the root, if not given */
    var r = this.window.location.href;
    /* Avoid input failures */    path = (path + '').replace('\\', '/');
    /* Check if there's a port in path (like 'http://') */
    if (path.indexOf('://') !== -1) {
        p = 1;
    }    /* Ok, there's not a port in path, so let's take the root */
    if (!p) {
        path = r.substring(0, r.lastIndexOf('/') + 1) + path;
    }
    /* Explode the given path into it's parts */    arr = path.split('/');
    /* The path is an array now */
    path = [];
    /* Foreach part make a check */
    for (var k in arr) {        /* This is'nt really interesting */
        if (arr[k] == '.') {
            continue;
        }
        /* This reduces the realpath */        if (arr[k] == '..') {
            /* But only if there more than 3 parts in the path-array.
             * The first three parts are for the uri */
            if (path.length > 3) {
                path.pop();            }
        }
        /* This adds parts to the realpath */
        else {
            /* But only if the part is not empty or the uri             * (the first three parts ar needed) was not
             * saved */
            if ((path.length < 2) || (arr[k] !== '')) {
                path.push(arr[k]);
            }        }
    }
    /* Returns the absloute path as a string */
    return path.join('/');
}
external links: original PHP docs | raw js source

Examples

Running

1
realpath('../.././_supporters/pj_test_supportfile_1.htm');

Should return

1
'file:/home/kevin/workspace/_supporters/pj_test_supportfile_1.htm'

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have realpath goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Kevin van Zonneveld
25 Oct '09 Permalink

q  @ cuisdy: We only port actual PHP functions, but given the amount of visitors coming here, I'm sure someone will run into your function and find it useful. So thanks for the code!

Gravatar
cuisdy
19 Oct '09 Permalink

q  No laughing at me, please...

Where it said "letsGo" it should say "letsStart". It's just the most silly variable name I could come up with, I know.

Gravatar
cuisdy
19 Oct '09 Permalink

q   Hi there, thanks for that script.

However, I was looking for a path resolver that would return a relative path resolved, not an absolute path resolved. I decided to do one myself and it works for me (though I haven't tested über weird inputs, so it's up for testing and improvements). Just in case someone wants it, here it is:

(hope it posts the code nicely formatted hehe)

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
20
function resolvePath( sPath ){
        
        sPath = sPath.replace(/\\/g,'/');               // Linux compatible
        sPath = sPath.replace(/\/\//g,'/');             // Fix double bars
        var aPathParts = sPath.split('/');              // Get parts of the path        
        for( var i=0, letsStart, sPart ; sPart = aPathParts[i] ; i++ ){
                if( sPart != '..'  ){
                        letsGo = true;
                        continue;                };
                if( letsStart && sPart == '..' ){
                        aPathParts.splice((i-1),2);
                        i=i-2;
                }        };
        
        return aPathParts.join('/');
        
};


Does PHP have a function like this, by the way?


Contribute a New function

More functions

In this category

basename
dirname
fclose
feof
fgetc
fgetcsv
fgets
fgetss
file
file_exists
file_get_contents
filemtime
filesize
fopen
fpassthru
fread
fseek
ftell
pathinfo
pclose
popen
readfile
» realpath
rewind

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: Anonymous and Shawn Houser.
<your name here>

Click here to lend your support to: phpjs and make a donation at www.pledgie.com !