-1

I've encountered something when trying to include/require a php script that's 2 directories back. It's not really a problem as I figured out a work around, however I'd love an explanation for what's happening.

Here's the file structure:

  • appCode
    • db.php (File I'm trying to include)
  • studentManagement
    • index.php
    • dep
      • getData.php (File I'm trying to include db.php into)

I want to include appCode/db.php in studentManagement/dep/getData.php.

getdata.php is executed with ajax from index.php

When I use:

require_once("../../appCode/db.php");

It doesn't work.

The only way it works is it I change directory first:

chdir("../");
require_once("../appCode/db.php");

Why won't the first method work? I've also tried using include instead of require but it's the same. I'm testing it on mamp 3.0.4.

Any help appreciated!!

4

2 に答える 2

0

これは、あなたrequire()include()そのバリアントが呼び出された最初のphpファイルに対して常に相対的であるためです(あなたの場合index.php

実際chdirにはそれとは何の関係もありません。これは次のとおりです。

require_once("../appCode/db.php");

が正しい呼び方です。

index.phpファイルが必要なときやディレクトリを操作するときのように、常に心の自己 (!) を配置してください。あなたの「アクティブディレクトリ」は、index.phpが配置されているディレクトリです。この現在の作業ディレクトリは、 http://php.net/manual/en/function.getcwd.phpでいつでも確認できます。getcwd()

于 2014-07-12T21:37:57.317 に答える
0

ルートからディレクトリ全体がわかっている場合は、次を使用できます。

http://php.net/manual/en/function.set-include-path.php

相対パスを使用する代わりに、インクルード パスから始まるファイルをいつでもインクルードまたは要求できるようになりました。

これを getData.php に入れることができます:

set_include_path ('/homepages/www/2/yourworkingpath');//Use your own directory
require_once 'appCode/db.php';

インクルードする必要がある場合は、他のファイルでも同じことを行うことができます。常にインクルード パスが使用されるため、変更先のディレクトリを探し続ける必要はありません。うまくいけば、これは少し役立ちます。

于 2014-07-12T22:39:40.840 に答える