我正在尝试检查包含文件中是否存在文件,但不确定路径是什么。
让我们绘制目录结构:
/public_html/
index.php
images/pics/pic1.jpg
subdir1/somefile1.php
subdir2/somefile2.php
shared/sharecodefile.php (file of functions that shared amoung all files)
首先在index.php中,当我这样做时:
file_exists("images/pics/pic1.jpg")
这很有效。但是,当包括sharecodefile.php时。我有点迷失这个文件现在假设的目录,因为它是当前的目录。如果我在index.php中包含此文件,
file_exists("images/pics/pic1.jpg")
这不起作用。我试过了:
file_exists("./images/pics/pic1.jpg");
file_exists("../images/pics/pic1.jpg");
file_exists($_SERVER['DOCUMENT_ROOT']."images/pics/pic1.jpg");
file_exists($_SERVER['DOCUMENT_ROOT']."/images/pics/pic1.jpg");
似乎无效。
更糟糕的是,我还需要在其他文件somefile1.php
+ somefile2.php
任何有关做什么的指示/解释都将非常感激。
答案 0 :(得分:1)
我以前有这段代码:
define( "PATH_ROOT", dirname(__FILE__) . "/");
<{1>}中的(假设你包含了index.php中的所有内容),而不是你只会使用:
index.php
当然,如果你需要它直接从file_exists( PATH_ROOT . 'images/pics/pic1.jpg');
开始工作,你可以这样做:
sharedcodefile.php
__FILE__
上的几句话。
答案 1 :(得分:0)
默认情况下,我相信shared/sharecodefile.php
会假设任何路径都相对于执行脚本(index.php
),所以简单地说:
file_exists('images/pics/pic1.jpg');
应该仍然有用。
但听起来你需要代码更便携,无论文件包含在何处都能正常工作。在这种情况下,您可能希望任何路径都相对于shared/sharecodefile.php
。
为此,请尝试:
file_exists(dirname(__FILE__).'/../images/pics/pic1.jpg');
或者您可以选择站点根目录的绝对路径:
file_exists($_SERVER['DOCUMENT_ROOT'].'/images/pics/pic1.jpg');
编辑:我刚注意到你说$_SERVER['DOCUMENT_ROOT']
不适合你。我不确定为什么,它在我的测试中有效。