【问题标题】:wrong path using 'require'使用“要求”的错误路径
【发布时间】:2023-03-19 15:11:01
【问题描述】:

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

我有这样的页面调用 bootstrap.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 中没有此类文件或目录:因此它仍在查找文件而不是目录。

可能是因为我使用了双重要求?我首先需要 description.php 中的 boostrap.php(效果很好),然后我需要来自这个 boostrap 的 class.php。 php (不采用绝对路径,而是对应文件boostrap.php的路径?

回答:

好的,它终于可以使用这个配置了:

使用 require 的第一个文件:

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

和boostrap.php:

    require_once(dirname(__FILE__). "/../class/$class.php");

【问题讨论】:

  • 如果像这样在路径中添加/inc/ 会怎样。 require "inc/class/$class.php";
  • 因为你调用了 /home/website/www/inc/bootstrap.php 中的require func 试试$path = dirname(__DIR__)."/class/$class.php";
  • @michltm 请注意,在本地和远程保持相同的结构会很好。如果不可能,我建议您将路径添加到现有/新配置文件。
  • @michltm 我重新阅读了您的错误:executing 脚本的路径是什么?
  • 你试过了吗:require './inc/bootstrap.php';

标签: php filepath


【解决方案1】:
  1. 正如在 cmets 中所说,使用绝对路径而不是 'inc/...' 是安全的,因为它是相对于当前类执行路径的,即:

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

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

  2. 我建议使用 require_once 以避免多次包含。

【讨论】:

  • 我尝试使用 dirname(FILE) 而不是 'inc/...' 但它并没有改变错误消息中的任何内容。使用 require_once dirname(FILE).'/../inc/bootstrap.php';导致警告:require_once(/home/website/www/../inc/bootstrap.php):无法打开流:第4行/home/website/www/description.php中没有这样的文件或目录致命错误: require_once():在 /home/website 中打开所需的 '/home/website/www/../inc/bootstrap.php' (include_path='.:/usr/share/php:/usr/share/pear') 失败/www/description.php 第 4 行。
  • 现在很清楚了。您的主要脚本位置是 /home/website/www/description.php
  • 您的引导程序位于 /home/website/www/inc/bootstrap.php 中,在这种情况下,您试图找到它是 /home/website/inc/bootstrap.php。解决方法: 1.将description.php放到/home/website/www的子目录下,将BASE_PATH定义改为
  • 目录名(文件).'/'
  • 请同时检查 inc dir 和 inc,bootstrap.php 文件属性中的 .htaccess 文件 - 可能它禁止读取或执行文件
猜你喜欢
  • 2020-11-03
  • 2011-04-18
  • 2015-07-18
  • 2015-06-08
  • 2016-05-22
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多