使用“要求”的错误路径


wrong path using 'require'

自从将我的网站从本地移动到在线后,我在使用 require 时遇到了路径问题。

我有调用引导程序的页面.php如下所示:

require 'inc/bootstrap.php';

而 boostrap.php 看起来像这样:

<?php
spl_autoload_register('app_autoload');
function app_autoload($class){
require "class/$class.php";
}

这在当地效果很好。

现在,在网上,我收到以下消息:

Warning: require_once(/home/website/www/class/functions.php): failed to open stream: No such file or directory in /home/website/www/inc/bootstrap.php on line 6
Fatal error: require_once(): Failed opening required '/home/website/www/class/functions.php' (include_path='.:/usr/share/php:/usr/share/pear') 
in /home/website/www/class/functions.php on line 6

所以我想,我应该在boostrap中放一个绝对的路径.php就像这样:

<?php
spl_autoload_register('app_autoload');
function app_autoload($class){
$path = $_SERVER['DOCUMENT_ROOT'] . "class/$class.php";
require_once "$path";
}

但是我得到了完全相同的错误。我不明白为什么它仍然在/home/website/www/inc/bootstrap 中查找.php而不是遵循/home/website/www/class/functions 的绝对路径.php ?

编辑:

在使用绝对路径测试不同的解决方案后,我仍然收到错误"/home/website/www/bootstrap 中没有这样的文件或目录.php:所以它仍在文件中查找而不是目录。

可能是因为我使用了双重要求吗?我首先需要 boostrap.php来自描述.php(工作正常(,然后我需要 class.php 来自这个 boostrap.php(它采用绝对路径,但与文件 boostrap 对应的路径.php

答:

好的,它终于可以使用此配置:

使用的第一个文件需要:

    require_once(dirname(__FILE__). '/inc/bootstrap.php');

和Boostrap.php:

    require_once(dirname(__FILE__). "/../class/$class.php");
  1. 正如注释中所说,使用绝对路径而不是"inc/..."是安全的,因为它是相对于当前类执行路径的,即:

    define ('BASE_PATH', dirname(__FILE__).'/../');
    

    然后使用BASE_PATH。{your_path} 以访问文件。

  2. 我建议使用require_once以避免多重内含物。