相对路径下的file_exists无法工作

7

file_exists 不起作用.. 我已经尝试使用 realpath.. 但是仍然有同样的问题

首先检查文件是否存在.. file_exists 返回 false,但文件仍然被加载

chdir(__DIR__.'/../..');

$file = 'frontend.php';

echo "$file\n";
if(file_exists($file)){
    echo "File found\n";
}
else{
    echo "File not found\n";
}

require $file;

输出

frontend.php
File not found
Contents of frontend.php

你的文件夹/文件结构是什么? - TMH
当前的include_path是什么?frontend.php相对于这个脚本在哪里? - VoteyDisciple
你确定文件已经成功加载了吗?你尝试过使用绝对路径吗? - Halayem Anis
3个回答

10
根据 php.net/file_exists 的说法,file_exists() 函数需要以下操作:

文件或目录的路径。

因此,尝试在路径前加上目录的路径:
if (file_exists(dirname(__FILE__) . $file)) {
    echo "File found\n";
}

4
从PHP 5.3+版本开始,您也可以使用__DIR__代替dirname(__FILE__) - Dezza
没错,但是让我们保持向后兼容,因为在这个例子中我们不确定使用的是哪个PHP版本。 - Egg

3
有时候file_exists()会缓存其结果。您可以尝试使用clearstatcache()来清除缓存。

0

尝试像这样做:

$file = dirname(__FILE__) . '/frontend.php';
if(file_exists($file)){
    //...
}

3
从 PHP 5.3+ 开始,您也可以使用 __DIR__ 替代 dirname(__FILE__) - Dezza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接