- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
- 4、该文档为VIP文档,如果想要下载,成为VIP会员后,下载免费。
- 5、成为VIP后,下载本文档将扣除1次下载权益。下载后,不支持退款、换文档。如有疑问请联系我们。
- 6、成为VIP后,您将拥有八大权益,权益包括:VIP文档下载权益、阅读免打扰、文档格式转换、高级专利检索、专属身份标志、高级客服、多端互通、版权登记。
- 7、VIP文档为合作方或网友上传,每下载1次, 网站将根据用户上传文档的质量评分、类型等,对文档贡献者给予高额补贴、流量扶持。如果你也想贡献VIP文档。上传文档
查看更多
这几天整理一份很乱的代码,这才意识到php对include处理不是一般的贱:别的编程语言在处理include中的相对目录时,都是以当前处理的文件作为基准。也就是说,如果A包含B,B包含C时,C再包含一个含相对路径的文件,那么路径是相对于C的。这样的处理很自然,符合人们的直觉,也便于开发出路径无关的程序包。
可是PHP不这样,它优先相对工作目录来处理,并且如果路径中包含. ..的话,则只相对于工作目录。也许PHP这样处理有它的理由,有谁知道的不妨告诉我。
下面是解决这一问题的几种方式:
__FILE__
__FILE__ always equals to the real path of a php script regardless whether its included.
__FILE__ helps you specify the file to include using relative path to the including file. 这种方法首选推荐。虽然你的include语句会因此要写得长一些,但是一个字,值!
PHP代码
?php include?dirname __FILE__ ./subdir; //dirname?return?value?does?not?contain?the?trailing?slash $_SERVER[DOCUMENT_ROOT]
This method allows you to specify a path relative to the web server doc_root for file inclusion. 这也是许多项目在采用的一种不错的方式,就我看来,缺点是,整个项目不方便移动。
例如你一开始放置在/,后来需要放到/abc/下的话,你要改文件(在一个公有文件中计算ROOT的位置,其他文件包含这个共有文件)。特别是当你同一份代码放多处时(例如一个测试环境和一个正式环境),你改文件也不好改。
PHP代码
?php if? !defined WETSITE_BASE_DIR define WETSITE_BASE_DIR,?$_SERVER[DOCUMENT_ROOT]./Clare/ ; require_once WETSITE_BASE_DIR.includes/global.inc.php ; chdir
The include looks for file relative to current working directory. We can use this feature. Its really a fancy way, but Im not sure whether its 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代码 ?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 set_include_path
This way is the most convenient way but its 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 expect
文档评论(0)