file_exists和包含相对路径的路径("/../")

Dud*_*ock 5 php file-exists

当我file_get_contents在类似的路径上使用时/a/path/to/a/../file.php,它可以很好地获取内容.如果我file_exists先调用(或is_filerealpath),则返回值表示该文件不存在.这似乎是什么问题?


编辑:以下是从评论到答案浓缩的一些其他信息:

  • 我使用php 5.5.6运行Mac OS X 10.9 ,因此安全模式应该不是问题 (它在版本5.4中被删除)
  • 我试着通过电话清理文件现金clearstatcache(true, $dir1)
  • 有问题的文件大小为362字节,但我在几个位置的混合中使用了几个不同的文件重现了这个问题.
  • open_basedir 在php.ini中被注释掉了
  • 该文件是本地的(我尝试的第一个文件与脚本位于同一目录中)
  • 问题存在于命令行(phpUnit)和浏览器中.
  • 问题中文件的权限是-rwxrwxrwx(我sudo-chmod-777ed文件)

这是一个创建行为的代码段:

$dir1 = '/a/path/to/a/../file.php';
$dir2 = '/a/path/to/file.php';

echo "File content dir1:\n";
echo file_get_contents($dir1);
echo "\ndir1 exists: ".(int)file_exists($dir1);

echo "\n\nFile content dir2:\n";
echo file_get_contents($dir2);
echo "\ndir2 exists: ".(int)file_exists($dir2);
Run Code Online (Sandbox Code Playgroud)

输出是:

File content dir1:
The actual content of the file. I promise!

dir1 exists: 0

File content dir2:
The actual content of the file. I promise!

dir2 exists: 1
Run Code Online (Sandbox Code Playgroud)

eli*_*ide 5

听起来你打开了安全模式并试图访问PHP在安全模式下运行时认为不安全的文件.从手册:

警告

对于因安全模式限制而无法访问的文件,此函数返回FALSE.但是,如果这些文件位于safe_mode_include_dir中,则仍可以包含这些文件.

编辑:如果/a/path/to/a/不是真正的路径,您也可以重现此行为.例如:

<?php

$dir1 = '/realDir/realDir2/filetoinclude.php';
echo "File content dir1:\n";
echo file_get_contents($dir1); // outputs file contents
echo "\ndir1 exists: ".(int)file_exists($dir1); // outputs 1

$dir2 = '/realDir/realDir2/realDir3/../filetoinclude.php';
echo "\n\nFile content dir2:\n";
echo file_get_contents($dir2); // outputs file contents
echo "\ndir2 exists: ".(int)file_exists($dir2); // outputs 1

$dir3 = '/realDir/realDir2/NotARealDirectory/../filetoinclude.php';
echo "\n\nFile content dir3:\n";
echo file_get_contents($dir3); // outputs file contents
echo "\ndir3 exists: ".(int)file_exists($dir3); // outputs 0
Run Code Online (Sandbox Code Playgroud)

这是因为file_exists需要遍历整个路径,因此它会查找丢失的目录并失败.我不确定file_get_contents到底有什么不同,我在谷歌上找不到多少,但它显然对路径的解析与file_exists的做法不同.