2013-02-04 89 views
1

我想找到一个文件是否存在于服务器的public_html文件夹中。file_exists - PHP返回动态public_html路径

第一次尝试:

if (file_exists('./local-config.php')) { 

,但是这只能当PHP文件调用上面的if语句是在同一文件夹......不会......

第二个尝试

if (file_exists($_SERVER['SERVER_NAME'].'/local-config.php')) { 

不工作...

第三尝试

if (file_exists('http://'. $_SERVER['SERVER_NAME'].'/local-config.php')) { 

也不起作用......

第四尝试

$_SERVER['DOCUMENT_ROOT'] seems to fall short of my public_html folder! 

任何想法?

我可以得到这个工作,如果我把完整的路径...例如

if (file_exists('/home/username/public_html/local-config.php')) { 

然而,这是没有好到我,因为脚本可以在多台服务器上使用,所以我需要的东西一般。

是否有可能让PHP动态返回public_html路径?

+0

你只需添加斜线/像“/local-config.php” – GGio

+0

我还没有试过,因为试过它会在根目录中寻找名为local-config.php的文件...例如与主目录相同的目录。 – Gravy

+0

不是真的取决于你的虚拟主机是如何设置的,对我来说,它看起来在public_html – GGio

回答

1

为此,我在我的应用程序中创建了一个全局变量。类似:

define('ROOT', dirname(__FILE__)); 

然后我用这与像的文件名:

ROOT . '/my_file.php' 
+0

完美,谢谢!如果我在public_html文件夹的根目录下运行,那么我包含的任何文件也将能够使用这个全局变量! :) – Gravy

0

尝试做这样的事情:

$path = dirname(__FILE__); 
// or just __DIR__ - it should be the same thing 

这将返回被呼叫的文件的完整路径。在PHP中,__FILE__是“magic constant”。从帮助页面:

The full path and filename of the file. If used inside an include, the name of 
the included file is returned. Since PHP 4.0.2, __FILE__ always contains an 
absolute path with symlinks resolved whereas in older versions it contained 
relative path under some circumstances. 

利用收集到的路径,你应该能够找出如何得到你想要的东西。