打开流失败:没有这个文件或目录,但实际上是有的!

9

我遇到了一些需要引入文件的问题,PHP告诉我这些文件不存在,但是当我扫描目录时,它告诉我它存在。我已经简化了代码使用require功能,但仍然无法正常工作。

这是我的设置:

root/
    test.php
    test/
        test2.php
        sub/
            test3.php

test.php

echo    'test';
require 'test/sub/test3.php';

test/test2.php(某些原因未被包含的文件)

echo    'test2';

test/sub/test3.php

echo    'test3';
/* 
because we are still on test.php, the include path is the root
that means the following would work:
require 'test/test2.php';
however I don't know this path in this file. (it's dynamic)
I thought this would work:
*/
set_include_path(dirname(__FILE__));
require '../test2.php';

编辑

好的,当我更改了这个:

set_include_path(dirname(__FILE__));
require '../test2.php';

to

set_include_path(dirname(__FILE__)."/../"));
require 'test2.php';

它运作了。wtf php?


现在这是我的输出:

testtest3
Warning: require(../test2.php) [function.require]: failed to open stream: No such file or directory in siteroot/test/sub/test3.php on line 6

Fatal error: require() [function.require]: Failed opening required '../test2.php' (include_path='siteroot/test/sub') in siteroot/test/sub/test3.php on line 6

如果我向test3.php添加以下代码:
echo '<pre>';
print_r(scandir(dirname(__FILE__).'/../'));
echo '</pre>';

我得到了如下结果(与预期相符):

Array
(
    [0] => .
    [1] => ..
    [2] => sub
    [3] => test2.php
)

我感觉自己快疯了,当我读到错误信息时,PHP告诉我一个文件不存在,而这个文件恰好就在那个位置。


仅为了调试,请跳过所有花哨的路径生成内容,尝试通过 require('/root/test/test2.php') 进行引用并查看结果。如果这样可以工作,那么问题就出在你的逻辑上。 - Marc B
是的,这个可以运行,问题在于我不知道/无法知道那个文件的路径。如果我能像那样写下所需的URL,我早就做了 ;) - Kokos
经常会遇到这个错误,为了快速排除故障,请按照以下步骤操作:https://dev59.com/LVoV5IYBdhLWcg3wL8Ww#36577021 - Vic Seedoubleyew
可能是重复的问题:无法打开流:没有这个文件或目录 - Vic Seedoubleyew
3个回答

6

更改

set_include_path(dirname(__FILE__));
require '../test2.php';

to

set_include_path(dirname(__FILE__)."/../");
require 'test2.php';

如果你读了我的问题(你复制粘贴的那部分),你会发现我知道那个方法可行,但这种方法对我来说不可行。 - Kokos
你的代码仍然有问题,但是由于你的修改,我能够找到一个解决方案。如果你可以将这个编辑放在你的问题中,我可以接受这个答案:set_include_path(dirname(__FILE__)."/../");require('test2.php');。因为某些原因,在include_path中放置../是可以工作的,而在require函数中放置../却不起作用。 - Kokos
现在有一个针对这个常见错误的故障排除清单,网址为: stackoverflow.com/a/36577021/2873507 - Vic Seedoubleyew

3
可能是符号链接的问题?尝试以下操作:
set_include_path(realpath(dirname(__FILE__))); // added realpath here

还可以尝试:

require(dirname(__FILE__) . '/../test2.php');

好的!我第一次看的时候不是这样的。 - iamjonesy
1
现在,在此常见错误的故障排除清单中可以找到:stackoverflow.com/a/36577021/2873507 - Vic Seedoubleyew

0
在类似的情况下,请检查目标(父级)文件夹是否存在。

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