18

Using __DIR__ and __FILE__ constants do not work in a symlinked situation. What is the workaround for this?

For example:

I have a file:

/home/me/modules/myfile.php

It is symlinked to:

/var/www/project/app/myfile.php

from in /home/me/modules/myfile.php i need to include a file that is located in /var/www/project

EDIT

To the suggestions of using realpath() - unfortunately this does not work.

var_dump(__DIR__);
var_dump(realpath(__DIR__));

both return exactly the same filepath

Marty Wallace
  • 34,046
  • 53
  • 137
  • 200

2 Answers2

6

Have you tried the following?

dirname($_SERVER['SCRIPT_FILENAME'])

In your case this will return: /var/www/project/app

Tim
  • 87
  • 1
  • 2
  • 1
    This should be the accepted answer – Mikael Lindqvist Jun 22 '15 at 20:09
  • 1
    This only works assuming PHP is running through a web server like Apache, not on the command line. – Greg Jun 09 '16 at 12:05
  • Not true. This works regardless of whether you're using a Web Server of Console. It's still going through a Server / SAPI -- in terms of a console, it will go through fpm-cgi rather than apache-cgi, for example. I have tested this and `$_SERVER['SCRIPT_FILENAME']` definitely works. – emma.fn2 Sep 19 '16 at 22:21
  • @emma.fn2 $_SERVER['SCRIPT_FILENAME'] returns file path passed as argument to php, not full path to file – ts. Nov 18 '16 at 17:14
  • 3
    This will fail to return the correct file path if you use this inside an included PHP file that is in a subfolder – Drakes Dec 21 '16 at 22:46
  • Using `SCRIPT_FILENAME` is mostly an equivalent to `realpath("./")` so is pretty much useless in a situation Drake describes. Example would be including a `config.php` from `test` directory. Where in the config you need to get scripts root. – Nux Jul 26 '19 at 16:16
0

You can use the realpath() function to expand symbolic links. My recommendation, however, would be to not use symlinks like this. (Add /var/www/project/app, or an appropriate parent directory, to your PHP include path instead.)

  • Im afraid realpath doesnt give me the symlinked location either – Marty Wallace Dec 07 '12 at 21:54
  • [`readlink()`](http://php.net/readlink) maybe? If not, I'm at a loss. –  Dec 07 '12 at 22:42
  • 1
    @duskwuff see http://stackoverflow.com/questions/13771021/php-dir-or-file-symlinked#comment18933995_13771021 OP wants opposite effect to realpath and readlink – dev-null-dweller Dec 07 '12 at 23:07
  • In that case, that isn't possible. There isn't even a unique answer -- there may be any number of symbolic links which all point to the same file. –  Dec 07 '12 at 23:14