require_once内部require_once创建路径问题


require_once Inside require_once Creates Path Issue

我有这样的条件:

  • 一个文件:/public_html/folderX/test.php有一行:require_once '../functions/sendemail.php'
  • /public_html/functions/sendemail.php有一行:require_once '../config.php'

config.php在这种情况下可以完美加载。

问题发生时,我试图添加functions/sendemail.php的文件,而不是在文件夹x,例如:

当我试图在public_html/test.php上添加require_once 'functions/sendemail.php'时,我得到了这个错误消息:

警告:require_once(../config-min.php) [function. php]在public_html/test.php中没有这样的文件或目录

如何使require_once '../config.php'在functions/sendmail .php中"独立"工作,因此无论它包含在任何文件中,这个"require_once"问题都不会再发生。

我尝试更改为'include_once',但仍然不起作用。

谢谢!

试试

require_once( dirname(__FILE__).'/../config.php')

尝试使用__DIR__获取脚本的当前路径。

require_once(__DIR__.'../config.php');

__DIR__仅适用于php 5.3

 __DIR__ 
The directory of the file. If used inside an include, the directory of 
the included file is returned. This is equivalent to dirname(__FILE__). 
This directory name does not have a trailing slash unless it is the root directory. 
(Added in PHP 5.3.0.)

我相信这里的相对路径名让你很头疼。相对路径(据我所知)是基于当前活动脚本的目录。当includingrequiring文件时,PHP不会将chdir放入文件夹中。对于这类事情,最好的建议(以我有限的经验)是尽可能使用绝对路径。比如:

require_once('../config.php');

将成为:

require_once('/home/myuser/config.php'); // Or wherever the file really is

您必须明白PHP将目录更改为最外层脚本的目录。当你使用相对路径时(例如,以./, ../开头的,或者不以/开头的),PHP将使用当前目录来解析相对路径。当您在代码中复制粘贴包含行时,这会导致问题。考虑以下目录结构:

/index.php
/admin/index.php
/lib/include.php

假设两个索引文件包含以下行:

include_once("lib/include.php");

/index.php被调用时,上面的行可以工作,但当/admin/index.php被调用时不能工作。

解决方案是不要复制粘贴代码,在include调用中使用正确的相对文件路径:

/index.php       -> include_once("lib/include.php");
/admin/index.php -> include_once("../lib/include.php");