最近使用PHP5發現一個include的路徑問題。

例如,a程式include引入子目錄下的b程式,而b程式又再include引入另一個子目錄下的c程式時。
依照以往習慣的寫法,只要以a程式所在位置去設定引入b程式及c程式的相對路徑,就不會有問題。

但是在PHP5卻會出現找不到檔案的情況,解決方法就是改成以 dirname(__FILE__) 取得相對路徑。

aa.php
001/bb.php
002/cc.php

aa.php

echo "This is aa.php<br />";
include("001/bb.php");

001/bb.php

echo "This is 001/bb.php<br />";
include("002/cc.php");

cc.php

echo "This is 002/cc.php";

PHP4的執行結果

This is aa.php
This is 001/bb.php
This is 002/cc.php

PHP5的執行結果

This is aa.php
This is 001/bb.php

Warning: include(002/cc.php) [function.include]: failed to open stream: No such file or directory in /001/bb.php on line 3

Warning: include() [function.include]: Failed opening '002/cc.php' for inclusion (include_path='/php5/PEAR;/php5') in /001/bb.php on line 3

解決的方法
將001/bb.php中include("002/cc.php")的語法改成以 dirname(__FILE__)取得相對路徑。

001/bb.php

echo "This is 001/bb.php<br />";
include(dirname(__FILE__)."/../002/cc.php");

改完後PHP5下再一次執行就正常了。

arrow
arrow
    全站熱搜

    yoonow 發表在 痞客邦 留言(0) 人氣()