PHP dirname returns symlink path

adamstrawson picture adamstrawson · Sep 25, 2012 · Viewed 15.1k times · Source

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'

Answer

manavo picture manavo · Sep 25, 2012

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));
}