[php] require_once의 상대 경로가 작동하지 않습니다.

나는 다음과 같은 구조를 가지고 있습니다.

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

include.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

미리 감사드립니다



답변

사용하다

__DIR__

스크립트의 현재 경로를 가져 오면 문제가 해결됩니다.

그래서:

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

이렇게하면 다른 폴더에서 PHP 스크립트를 실행할 수 있으므로 상대 경로가 작동하지 않는 경우를 방지 할 수 있습니다.

편집 : 슬래시 문제 수정


답변

PHP 버전 5.2.17의 __DIR__경우 작동하지 않습니다 .PHP 5.3에서만 작동합니다.

그러나 이전 버전의 PHP의 경우 dirname(__FILE__)완벽하게

예를 들어 다음과 같이 작성하십시오.

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


답변

내 경우에는 그와 함께도하지 작업을 수행 __DIR__하거나 getcwd()이 잘못된 경로를 따기 유지, 나는이 프로젝트의 절대 기본 경로에 필요한 모든 파일에 costant을 정의하여 해결 :

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';


답변