[ PHP ] require_once 関数 Warning: failed to open stream: No such file or directory in ・・・

Pocket

require_once 関数で上位のディレクトリ階層にある PHP ファイルを相対パス指定で読み込もうとするとワーニングが発生します。

Warning: require_once(../parent.php) [function.require-once]:failed to open stream: No such file or directory in ・・・

スポンサーリンク

このワーニングは下記のような構成の場合に出力されます。

ワーニングとなるファイル構成例


parentDir/
 |
 |--- parent.php
 |
 |--- childDir/
       |
       |-- child.php

child.php から parent.php を読み込む

// 相対パス指定で読み込み
require_once '../parent.php';

// ワーニングが出力される
// Warning: require_once(../parent.php) [function.require-once]:failed to open stream: No such file or directory in ・・・

ワーニングが出ないようにする対策案を 2つ示します。

[ 対策方法1 ] 絶対パスで指定

1つ目は dirname 関数を使用して、ファイルが存在するディレクトリを元に絶対パスで指定する方法です。

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

[ 対策方法2 ] php.ini の include_path にパスを追加

php.ini の include_path に parentDir へのパスを追加します。child.php では parentDir から下層への相対パス指定とする方法です。Web サーバが apache であれば httpd.conf や .htaccess でも設定できます。

php.ini
include_path = ".:/path/to/parentDir:・・・"
child.php
require_once 'childDir/parent.php';
参考
スポンサーリンク


Pocket

Leave a Comment

Your email address will not be published. Required fields are marked *