PHP dirname returns symlink path

2019-02-13 08:58发布

Say I have a symlink from '/one/directory/' to '/two/directory/'.

If I echo dirname(dirname(\__FILE__)), it returns '/one/directory/'.

What is the best method to return '/two/directory'?

Example usage:

Vhost 'example.com' pointing to `'/two/directory'

example.com/hello_world.php

<?php 
    echo dirname(dirname(__FILE__));
?>

Returns: '/one/directory'

Expected results: '/two/directory'

5条回答
Luminary・发光体
2楼-- · 2019-02-13 09:09

Use readlink($path) to read the target of symbolic link.

<?php 
    echo readlink(dirname(__FILE__));
?>
查看更多
冷血范
3楼-- · 2019-02-13 09:25

Use the readlink function? http://php.net/manual/en/function.readlink.php

You can check if it is a symlink with is_link: http://php.net/manual/en/function.is-link.php

if (is_link($link)) {
    echo(readlink($link));
}
查看更多
虎瘦雄心在
4楼-- · 2019-02-13 09:29
<?php

function getRealFile($path) {
    return is_link($path) ? readlink($path) : $path;
}

$path = getRealFile(dirname(__FILE__));

Documentation:

http://php.net/manual/en/function.is-link.php
http://php.net/manual/en/function.readlink.php

查看更多
一夜七次
5楼-- · 2019-02-13 09:29

Maybe with realpath() ? http://php.net/manual/en/function.realpath.php

Edit : readlink seems to be a better answer :)

查看更多
Evening l夕情丶
6楼-- · 2019-02-13 09:31

What is the best method to return '/two/directory'?

Use the https://github.com/logical-and/symlink-detective and

<?php 

echo SymlinkDetective::detectPath(dirname(dirname(__FILE__)));

will return '/two/directory'

查看更多
登录 后发表回答