PHP 自动加载器的文件路径错误

PHP file path error for autoloader

这是我的 cpanel 网络服务器上的文件结构

root
   > vendor
         > autoload.php
   > public_html
         > folder
               > file2.php
         > script_folder
               > include_file.php
         > file1.php

里面include_file.php我有

 require_once('../vendor/autoload.php');

file1.php 和 file2.php 都包含对 include_file.php

的相同调用
 require_once($_SERVER["DOCUMENT_ROOT"]."/script_folder/include_file.php");

这在我 运行 file1.php 时工作正常但是当我 运行 file2.php 我收到以下错误消息。

No such file or directory Fatal error: require_once(): Failed opening required '../vendor/autoload.php' (include_path='.:/opt/cpanel/ea-php71/root/usr/share/pear') in /lvl1/lvl2/public_html/script_folder/include_file.php

但是,如果我在 include_file.php 中将 require_once('../vendor/autoload.php'); 更改为 require_once('../../vendor/autoload.php');,则 file2.php 有效,而 file1.php 无效。它显示了类似的错误。

我知道这是一个文件路径问题,但我不明白为什么。 include_file.php 中的路径不应该总是相同的,无论哪个文件调用它;即 file1.php 或 file2.php?

我的看法是 include_file.php 调用了实际的 require_once 语句,但是,我看到的行为让我认为 require_once 语句正在 运行 从 file1.php 或 file2.php 导致文件路径错误。

有人可以澄清一下吗?


更新:在 include_file.php 里面我试过使用:

require_once($_SERVER["DOCUMENT_ROOT"] . '/vendor/autoload.php');

require_once(dirname(__FILE__).'/vendor/autoload.php');

这些都不起作用,因为 return public_html 都是主工作目录。我的 vendor 文件夹在主工作目录之外。

什么是 returned 是这样的:

/script_folder/vendor/autoload.php

我知道我可以简单地在 file1.phpfile2.php 的开头包含正确的文件路径,但是,我试图找出一种方法来减少我需要的每个文件的数量将文件指向 include_file.php,然后让 include_file.php 完成其余工作。

我的 include_file.php 文件包含其他几个对我服务器上其他脚本的要求语句。有点像迷你自动装弹机。除了我在这里遇到问题的 autoload.php 之外,所有其他 require 语句都可以正常工作。

我能看到的唯一区别是我的其他脚本在我的 public_html 文件夹中,而我的 autoload.php 文件位于 public_html 之外。

假设您使用的是 Composer,您只需要在 file1.php 中要求 "autoload.php" 一次,并且该文件应该在开头下方的文件顶部包含一个名称空间,例如 namespace App; PHP 标签。随后,file2.php 应包含 namespace App\folder;included_file.php 应包含 namespace App\script_folder;

命名空间也应该在 composer.json 中定义,如下所示:

"autoload": {
    "psr-4": {
        "App\": "public_html/"
    }
}

这似乎工作得很好。猜猜我需要使用绝对路径而不是相对路径。

include_file.php:

$autoload = str_replace('public_html','vendor/autoload.php',$_SERVER["DOCUMENT_ROOT"]);
include($autoload);

它允许我调用:

require_once($_SERVER["DOCUMENT_ROOT"]."/script_folder/include_file.php");

来自我的 public_html 文件夹中的任何文件。


in include_file.php $_SERVER["DOCUMENT_ROOT"] returns /lvl1/lvl2/public_html(公开可见文件夹的完整服务器路径)

然后我将 public_html 替换为自动加载器的路径 vendor/autoload.php