在PHP中有带有未解析符号链接的脚本路径吗? [英] Have script path with unresolved symlinks in PHP?
问题描述
假设我们有一个包含以下路径的网络目录:
Let's say we have a web directory with the following paths:
framework/
index.php
...
instance/
index.php -> ../framework/index.php (symlink)
...
如果我们现在请求(...)/instance/index.php
,PHP将解析符号链接并将__FILE__
设置为(...)/framework/index.php
If we now make a request for (...)/instance/index.php
PHP will resolve the symlinks and set __FILE__
as (...)/framework/index.php
有没有解决的办法,例如dirname(__FILE__)
是(...)/instance
吗?
Is there a way around this so e.g. dirname(__FILE__)
would be (...)/instance
?
编辑:由于已经指出,实际上我不确定PHP本身是否在解决链接或其他问题.就我而言,我将nginx
用作Web服务器,而将php-fpm
用作FastCGI.
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.
(背景是我希望有多个引用公共代码库的CMS或Framework实例.)
推荐答案
您的案例的最佳近似值是dirname($_SERVER['SCRIPT_FILENAME'])
以获取"instance"目录,如果您可以在文档中接受有关
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:
不能保证每个Web服务器都会提供其中的任何一个; 服务器可能会省略其中一些,或提供此处未列出的其他服务器.
There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here.
此外,PHP手册也未明确承诺该符号链接将被保留,但这似乎是事实(除非您的服务器当然认为不是这样).另请参见此答案.
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.
(注意:这也可以在CLI模式下工作.如果脚本是通过相对路径(到CWD的)启动的,PHP会保持这种方式,所以您可能会以."结尾.)
(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.)
但是,对于一般问题(获取保留了符号链接的 any 脚本目录),此方法不起作用.它仅适用于通过HTTP到达的脚本.由于以后您include
所执行的其他所有脚本都将具有相同的$_SERVER['SCRIPT_FILENAME']
(当然),无论它们位于何处,如果dirname($_SERVER['SCRIPT_FILENAME'])
位于其他位置,则会产生错误的目录...
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...
我认为PHP(从v7.2开始)没有针对此问题的解决方案.
I don't think PHP has a solution for that today (as of v7.2).
(最初您是正确的:无论服务器是什么,PHP都在为__FILE__
做符号链接解析.而且
(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.)
这篇关于在PHP中有带有未解析符号链接的脚本路径吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!