Need_once 中的相对路径不起作用

我有以下结构

otsg
> class
> authentication.php
> database.php
> user.php
> include
> config.inc.php
> encryption.php
> include.php
> session.php
> index.php
> registration.php

Php 文件包含以下内容

ini_set('display_errors', 1);
error_reporting(E_ALL);


ini_set('include_path',ini_get('include_path').':/Applications/MAMP/htdocs/otsg/:');
require_once 'config.inc.php';
require_once '../class/database.php';
require_once '../class/user.php';
require_once 'encryption.php';
require_once 'session.php';
require_once '../class/authentication.php';

并且在 index.php 页面中包含

require_once 'include/include.php';

当我打开 index.php 页面时,会得到以下警告和致命错误。我不明白是什么导致了这个错误。当我给出绝对路径时,它是有效的。但我相信绝对路径不是个好主意。

Warning: require_once(../class/database.php) [function.require-once]: failed to open stream: No such file or directory in /Applications/MAMP/htdocs/otsg/include/include.php on line 9


Fatal error: require_once() [function.require]: Failed opening required '../class/database.php' (include_path='.:/Applications/MAMP/bin/php5.3/lib/php:/Applications/MAMP/htdocs/otsg/include/:') in /Applications/MAMP/htdocs/otsg/include/include.php on line 9

先谢谢你

118072 次浏览

使用

__DIR__

获取脚本的当前路径,这应该可以解决您的问题。

所以:

require_once(__DIR__.'/../class/user.php');

This will prevent cases where you can run a PHP script from a different folder and therefore the relatives paths will not work.

编辑: 斜杠问题已修复

对于 php 版本5.2.17 __DIR__将不工作,它将只与 php 5.3工作

但是对于老版本的 php dirname(__FILE__)来说就完美了

比如这样写

require_once dirname(__FILE__) . '/db_config.php';

在我的情况下,它不工作,即使与 __DIR__getcwd()它总是选择错误的路径,我解决了每个文件中定义一个成本,我需要与项目的绝对基本路径:

if(!defined('THISBASEPATH')){ define('THISBASEPATH', '/mypath/'); }
require_once THISBASEPATH.'cache/crud.php';
/*every other require_once you need*/

我有一个带有 php 5.4.10的 MAMP,我的文件夹层次结构是基于:

q.php
w.php
e.php
r.php
cache/a.php
cache/b.php
setting/a.php
setting/b.php

....

我只是遇到了同样的问题,在这个问题上,一切都运行良好,直到我在另一个包含中包含了一个包含。

require_once '../script/pdocrud.php';  //This worked fine up until I had an includes within another includes, then I got this error:
Fatal error: require_once() [function.require]: Failed opening required '../script/pdocrud.php' (include_path='.:/opt/php52/lib/php')

解决方案1. (不希望对我的公用 html 文件夹名进行硬编码,但它可以工作) :

require_once $_SERVER["DOCUMENT_ROOT"] . '/orders.simplystyles.com/script/pdocrud.php';

解决方案2. (上面关于 DIR 只能从 php 5.3开始工作,但是可以工作的不希望的注释) :

require_once __DIR__. '/../script/pdocrud.php';

解决方案3. (我看不到任何缺点,它在我的 php 5.3中工作得很完美) :

require_once dirname(__FILE__). '/../script/pdocrud.php';