【问题标题】:PHP can't find file even though it existsPHP 找不到文件,即使它存在
【发布时间】:2020-08-16 17:38:39
【问题描述】:

我在带有 Apache 2 的 Ubuntu 18.04 上运行 PHP 7.4.9。

我的 PHP 错误日志中出现此错误:

"PHP 致命错误:require_once(): 需要打开失败 'HTMLPurifier.auto.php' (include_path='(其他 dirs):/usr/share/php:(other dirs)') 在 /var/www/testing.php 第 8 行, 引用者:http://localhost:8080/testing.php"

所以我检查了/usr/share/php中是否存在该文件:

# ls -lah /usr/share/php
> -rwxrwxrwx   1 www-data www-data  274 Aug 15 15:53 HTMLPurifier.auto.php

所以它就在那里。权限是 777,因为我在尝试解决问题时更改了它们。

然后我在浏览器中访问了一个phpinfo(); 文件并检查了该目录是否在包含路径中并且open_basedir 为空:

Directive       Local Value   Master Value
include_path    (other dirs)  .:/usr/share/php
open_basedir    no value      no value

然后我创建了另一个 PHP 文件并写了这个来检查 php 是否可以看到该文件:

<?php

clearstatcache();

$dir = '/usr/share/php/';
$filename = 'HTMLPurifier.auto.php';
$fullpath = $dir . $filename;

var_dump($dir);
var_dump($filename);
var_dump($fullpath);

var_dump(is_dir($dir));

$all_files = scandir($dir);

var_dump($all_files);
var_dump(file_exists($fullpath));
var_dump(file_exists($dir . $all_files[12]));

当我在浏览器中访问它时,我得到:

string(15) "/usr/share/php/" // $dir

string(21) "HTMLPurifier.auto.php" // $filename

string(36) "/usr/share/php/HTMLPurifier.auto.php" // $fullpath

bool(true) // is_dir($dir)

// $all_files
array(40) {
  (other files)
  [12]=> string(21) "HTMLPurifier.auto.php"
}

bool(false) // file_exists($fullpath)

bool(false) // file_exists($dir . $all_files[12])

所以 PHP 可以扫描目录,可以看到那里的文件,但说它(或目录中的任何其他文件)不存在。我测试了将/var/www 中的文件传递给file_exists 并且它有效。我也尝试重命名文件,但没有任何结果。

什么给了?


编辑:使用strace php test.php 运行上述脚本(如@Progman 所建议)给了我:

access("/usr/share/php/HTMLPurifier.auto.php", F_OK) = -1 EACCES (Permission denied)
write(1, "bool(false)\n", 12bool(false)
)           = 12

access("/usr/share/php/HTMLPurifier.auto.php", F_OK) = -1 EACCES (Permission denied)
write(1, "bool(false)\n", 12bool(false)
)           = 12 

所以这是一个权限问题。以 root 身份运行脚本。

$ ls -lah /user/share
drw-rw-rw-  20 root root 4.0K Aug 16 11:52 php

所以我尝试了sudo chmod 777 /usr/share/php 并且脚本有效。少一点(例如 776),我就被拒绝了。知道我应该如何设置这些权限吗?

【问题讨论】:

  • 你在运行 SELinux 吗?如果是:运行ls -Z /usr/share/php/ 并查看它的外观;我相信应该是httpd_sys_content_t。如果 Apache 默认访问不允许上下文,SELinux 将在不考虑权限的情况下阻止访问。
  • 通过命令行命令“php”调用测试php脚本时能读取文件吗?当您收到相同的错误消息时,您可以运行strace php script.php 并将输出添加到您的问题中吗?
  • @FelipeZavan 作为普通用户运行时,请将strace php script.php 的输出添加到您的问题中。
  • 尝试chmod 0755 HTMLPurifier.auto.php 然后chown www-data:root HTMLPurifier.auto.php。是这样的吗?
  • @FelipeZavan 为什么目录/usr/share/php/ 没有--x 权限集(即“搜索”目录)?通常它类似于755,但在您的chmod 代码中类似于666

标签: php


【解决方案1】:

在 linux 中,像您的普通工作用户或网络服务器分配的用户这样的普通用户需要目录权限“搜索”,即--x 或位掩码1,才能访问目录内的文件。权限-r- 或位掩码2 将只允许您读取目录中的文件名。

要解决这个问题,您必须将目录/usr/share/php 的chmod 更改为755

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    相关资源
    最近更新 更多