PHP中include路徑的解決方法匯總
當(dāng)前位置:點(diǎn)晴教程→知識管理交流
→『 技術(shù)文檔交流 』
這幾天整理一份很亂的代碼,這才意識到php對include處理不是一般的賤:別的編程語言在處理include中的相對目錄時,都是以當(dāng)前處理的文件作為基準(zhǔn)。也就是說,如果A包含B,B包含C時,C再包含一個含相對路徑的文件,那么路徑是相對于C的。這樣的處理很自然,符合人們的直覺,也便于開發(fā)出路徑無關(guān)的程序包。 可是PHP不這樣,它優(yōu)先相對工作目錄來處理,并且如果路徑中包含. ..的話,則只相對于工作目錄。 下面是解決這一問題的幾種方式:
__FILE__ always equals to the real path of a php script regardless whether it's included. __FILE__ helps you specify the file to include using relative path to the including file. <?php include dirname(__FILE__).'/subdir'; //dirname return value does not contain the trailing slash ?>
This method allows you to specify a path relative to the web server doc_root for file inclusion. 例如你一開始放置在xxx.com/,后來需要放到xxx.com/abc/下的話,你要改文件(在一個公有文件中計算ROOT的位置,其他文件包含這個共有文件)。 <?php if (!defined("WETSITE_BASE_DIR")) define("WETSITE_BASE_DIR", $_SERVER['DOCUMENT_ROOT'].'/Clare/'); require_once(WETSITE_BASE_DIR.'includes/global.inc.php'); ?>
The include looks for file relative to current working directory. We can use this feature. It's really a "fancy" way, but I'm not sure whether it's safe all the time. Who knows? rainfalling at yahoo dot com (21-Sep-2005 01:06) This is yet another way to include files relative to the current file. I find it easier if you have a lot of includes. <?php $prewd = getcwd(); // get the current working directory chdir(realpath(dirname(__FILE__))); // change working directory to the location of this file include('includedfile.php'); // include relative to this file chdir($prewd); // change back to previous working dir ?>
This way is the most convenient way but it's not without flaws. First, not in all cases you have permission to change server configuration. Second, if there are many path specified in include_path, the actually included file may not be the one you expected because there may be files of the same name under different directories.
This almost the best way if your scripts commonly need a startup script. We can do a lot of useful things in the startup script, for examples, define constants, load configurations. But it's not always OK to change the php.ini settings. Remember the most adaptive application should be as independent from configs as possible. 該文章在 2012/8/6 9:29:26 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |