Mridang Agarwalla
Mridang Agarwalla

Reputation: 45128

How can I fetch the parent directory of the current symlinked directory?

I would like to get an absolute path of the current script which is actually symlinked.

The __FILE__ always points to the real file and not the symlink, while $_SERVER['SCRIPT_FILENAME'] points to the symlink.

I would like to go up the directory tree of the $_SERVER['SCRIPT_FILENAME'] but appending the /.. and invoking realpath navigates up the directory tree of the actual file.

Here's the code I'm running:

print dirname(__FILE__);
print '<br />';
print realpath(dirname(__FILE__) . '/..');
print '<br />';
print $_SERVER['SCRIPT_FILENAME'];
print '<br />';
print realpath(dirname($_SERVER['SCRIPT_FILENAME']) . '/..');

The code above outputs:

/Users/mridang/Hello/Application
/Users/mridang/Hello
/Applications/MAMP/htdocs/1609/modules/mymodule/ctrl.php
/Users/mridang/Hello

How can I navigate up the directory of the symlink without resolving the symlink?

Upvotes: 0

Views: 975

Answers (2)

AnotherGuy
AnotherGuy

Reputation: 615

From what I know you can use the native PHP function readlink. This should resolve symlinks.

You can also check this answer from StackOverflow.

Upvotes: 2

Rajat Arora
Rajat Arora

Reputation: 606

Use readlink($path) to read the target of symbolic link. You can check if it is a symbolic link with is_link:

Examples:

<?php
    if (is_link($link)) {
       echo(readlink($link));
    }

    echo readlink(dirname(__FILE__));
?>

Upvotes: 0

Related Questions