1

我有一个函数可以检查用户提供的文件名是否在 /opt/ 目录下。它使用真实路径,因此出于安全原因,用户不能传入类似“../etc/passwd”的内容。

function check_file_path($relative_filename) {
    $abspath = realpath('/opt/' . $relative_filename);
    return ($abspath && strpos($abspath , '/opt/') === 0);
}

现在,如果文件在 fs 上不存在,realpath 将返回 false。当 PHPUnit 运行时(在开发机器上,而不是在服务器上),路径不存在,因此我们无法进行正面测试。

我已经研究过 vfsstream,但它与 realpath() 不兼容

org\bovigo\vfs\vfsStream::setup('home');
$file = org\bovigo\vfs\vfsStream::url('home/test.txt');
file_put_contents($file, "The new contents of the file");
$abspath = realpath('vfs://home/test.txt');
// $abspath will be false

有什么建议可以模拟文件系统以便 realpath 可以工作吗?

4

1 回答 1

1
  1. 您可以使用runkit。它是 php 的扩展。

  2. 但是,如果您的函数在任何命名空间内调用,您可以在该命名空间中定义自己的函数。

于 2013-06-07T01:39:56.733 回答