PHP——访问网站根目录解决方案
問題描述?
其他編程語言在處理include中的相對(duì)目錄時(shí),都是以當(dāng)前處理的文件作為基準(zhǔn)。即如果A包含B,B包含C時(shí),C再包含一個(gè)含相對(duì)路徑的文件,那么路徑是相對(duì)于C的。這樣的處理很自然,符合人們的直覺,也便于開發(fā)出路徑無關(guān)的程序包。
可是PHP不這樣,它優(yōu)先相對(duì)工作目錄來處理,并且如果路徑中包含. ..的話,則只相對(duì)于工作目錄。
解決方案
下面是解決這一問題的幾種方式:
- __FILE__ ? 返回的是一個(gè)物理的真實(shí)路徑
__FILE__ ?always equals to the real path of a php script ?regardless whether it's included.
- $_SERVER['DOCUMENT_ROOT'] ? ? 返回網(wǎng)站根目錄,跟網(wǎng)站配置文件的 DOCUMENTROOT的值一致.
This method allows you to specify a path?relative to the web server doc_root?for file inclusion.?
這也是許多項(xiàng)目在采用的一種不錯(cuò)的方式,就我看來,缺點(diǎn)是,整個(gè)項(xiàng)目不方便移動(dòng)。
例如你一開始放置在xxx.com/,后來需要放到xxx.com/abc/下的話,你要改文件(在一個(gè)公有文件中計(jì)算ROOT的位置,其他文件包含這個(gè)共有文件)。
特別是當(dāng)你同一份代碼放多處時(shí)(例如一個(gè)測試環(huán)境和一個(gè)正式環(huán)境),你改文件也不好改。
- chdir()
這種方式感覺稍嫌麻煩了點(diǎn),隨時(shí)要記得恢復(fù)工作目錄也不是容易的事。寫完這句話后,我隨后寫了幾個(gè)測試文件,發(fā)現(xiàn)這種方式的最重要缺點(diǎn)不在麻煩,
而在它的副作用:改變了工作目錄,這會(huì)導(dǎo)致程序邏輯出錯(cuò)。
- set_include_path()
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.?
這是最方便的方式,但不是沒有缺點(diǎn)。首先,有時(shí)候你不見得有權(quán)限修改配置。其次,當(dāng)不同路徑下的文件名有重復(fù)的時(shí)候,你會(huì)被搞糊涂的(就算你不會(huì),你的維護(hù)者呢)。
- auto_prepend_file and auto_append_file in php.ini
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.??
如果你每個(gè)腳本都需要包含一個(gè)通用腳本的話,這幾乎是最好的方式,但是,缺點(diǎn)還是,與配置相關(guān),不夠獨(dú)立。
- realpath()?
realpath("./") 用于獲取當(dāng)前網(wǎng)站根目錄的絕對(duì)路徑,如:c:\wamp\www\網(wǎng)站名稱\
因此我們可以將include("../B/2.php");改成include(realpath("./")."B/2.php");
參考文章
https://www.cnblogs.com/w10234/p/5415695.html
https://blog.csdn.net/suleil1/article/details/49470979
https://www.w3school.com.cn/php/php_includes.asp
總結(jié)
以上是生活随笔為你收集整理的PHP——访问网站根目录解决方案的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Liunx——校准时间、时间同步(ntp
- 下一篇: PHP/AJAX——登录页面与登录信息提