Have script path with unresolved symlinks in PHP?

梦想的初衷 提交于 2019-12-25 07:35:14

问题


Let's say we have a web directory with the following paths:

framework/
    index.php
    ...
instance/
    index.php -> ../framework/index.php (symlink)
    ...

If we now make a request for (...)/instance/index.php PHP will resolve the symlinks and set __FILE__ as (...)/framework/index.php

Is there a way around this so e.g. dirname(__FILE__) would be (...)/instance?

EDIT: Since it has been pointed out, I'm actually not sure if PHP itself is resolving the links or something else. In my case I'm using nginx as a webserver with php-fpm as FastCGI.

(The background is that I want to have multiple instances of a CMS or Framework referencing a common code base.)


回答1:


The best approximation for your case is dirname($_SERVER['SCRIPT_FILENAME']) to get the "instance" dir, if you can live with the general warning in the doc about the $_SERVER vars:

There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here.

Also, the PHP manual does not explicitly promise that symlinks will be preserved, but that seems to be the case (unless of course your server thinks otherwise). See also this answer.

(Note: this also works in CLI mode. If the script was launched via a relative path (to the CWD), PHP will keep it that way, so you may end up with "." then.)

However, for the general problem (of getting any script's dir with symlinks preserved), this doesn't work. It only works for the script that has been reached via HTTP. Since any other scripts you include later on will all have the same $_SERVER['SCRIPT_FILENAME'] (of course), regardless of their location, dirname($_SERVER['SCRIPT_FILENAME']) will yield the wrong dir if they are located elsewhere...

I don't think PHP has a solution for that today (as of v7.2).

(And you were correct initially: PHP is doing the symlink-resolving for __FILE__, irrespective of your server. And it's unlikely that this would ever change, because it has stayed this way for too long (and too much code depends on it), even though there's realpath() if we wanted the resolved path, while there's no bullet-proof solution for the symlinked case.)



来源:https://stackoverflow.com/questions/37446267/have-script-path-with-unresolved-symlinks-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!