【问题标题】:PHP file path error for autoloader自动加载器的 PHP 文件路径错误
【发布时间】:2018-03-06 12:47:14
【问题描述】:

这是我的 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 时我收到以下错误消息。

没有这样的文件或目录致命错误:require_once(): Failed opening required '../vendor/autoload.php' (include_path='.:/opt/cpanel/ea-php71/root/usr/share/pear ') 在/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');

这些都不起作用,因为它们都返回 public_html 作为主工作目录。我的vendor 文件夹位于主工作目录之外。

返回的是这样的:

/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 之外。

【问题讨论】:

标签: php filepath require-once


【解决方案1】:

假设您使用的是 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/"
    }
}

【讨论】:

    【解决方案2】:

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

    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 文件夹中的任何文件。


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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2023-03-19
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多