php文件之间相互引用路径问题的一般处理方法

来源:互联网 发布:淘宝发布图片规则 编辑:程序博客网 时间:2024/06/01 14:20

基础知识

  

/前面的点式来表现路径的地址,一般来说都是相对路径    因为当你的文件上到外网上以后,你本地的路径可能和外网的路径不同    所以不能用绝对路径,用相对路径就可以找到文件  一般情况如下:     ./    表示当前目录下     ../   表示上一级目录     /     表示根目录打个比方  /root/first/second     你用 / 就表示 在/root 路径下      ./first  表示first路径下 就不需要写成 /root/fiest     同样的道理 ../second  表示 /root/first/second    用这个表示 主要是去掉根目录的繁琐。

在其他web编程语言中相对路径都是以当前处理文件目录为基准,而在php中并非如此。php中相对路径是以当前工作目录为基准的,并非以当前处理文件目录为基准,这样在开发过程中带来了不少的麻烦。比如会遇到一下问题

aaa

      a.php

      bbb

            b.php

            b1.php

            ccc

                 c.php

以上目录中c.php中require(../b1.php),在a.php中require(bbb/ccc/c.php),这样就会出错,因为a.php中会在../中找b1.php,会找不到b1.php文件而报错,解决以上引用问题的一般做法有两种:

 

一、在a.php中加上define('ROOT_PATH',dirname(__FILE__));

      之后再加上
     require ROOT_PATH/bbb/ccc/c.php

    

二、 在根目录下新建一个文件global.php,内容包含chdir(dirname(__FILE__));

       在每个文件中都将这个global.php包含进来。

 

综上所述,如果a文件引用了非同目录的b文件,且这个a文件将被非同目录的c文件引用,那么就要在a文件中用dirname(__FILE__)来包含b文件,否则在执行c文件时,会报错找不到b文件。


补充用法:

5、使用下面的这个语句可以把当前目录设置为当前文件的目录路径,也较为方便,尤其是交叉引用的时候非常有用。

chdir(dirname(__FILE__));

6、对于使用虚拟主机的用户可以在包含文件之前使用set_include_path()函数,比如:

set_include_path(‘./’.PATH_SEPARATOR.dirname(__FILE__));

require_once(‘include/cfg.php’);

7、 通过辅助设置php配置文件中的的include_path参数进行查询路径,include_path是指将要用到的包含文件所在的目录,可以将经常 include文件放到一个统一的目录里,然后把这个目录设置在配置文件php.ini的include_path参数后面,在需要使用这些包含文件的时 候只需要包含其名称即可,比如<?php include "metsky_cfg.php"; ?>就可以了,而实际上metsky_cfg.php文件则是存在设置的文件目录里。

附PHP.ini文件中include_path部分内容:

;;;;;;;;;;;;;;;;;;;;;;;;;
; Paths and Directories ;
;;;;;;;;;;;;;;;;;;;;;;;;;

; UNIX: "/path1:/path2"
;include_path = ".:/php/includes"
;
; Windows: "\path1;\path2"
;include_path = ".;c:\php\includes"
;
; PHP's default setting for include_path is ".;/path/to/php/pear"
; http://php.net/include-path
include_path = ".;D:\xampp\php\PEAR"

; The root of the PHP pages, used only if nonempty.
; if PHP was not compiled with FORCE_REDIRECT, you SHOULD set doc_root
; if you are running php as a CGI under any web server (other than IIS)
; see documentation for security issues.  The alternate is to use the
; cgi.force_redirect configuration below
; http://php.net/doc-root
doc_root =

; The directory under which PHP opens the script using /~username used only
; if nonempty.
; http://php.net/user-dir
user_dir =

; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
; extension_dir = "ext"
extension_dir = "D:\xampp\php\ext"

......

8、通过.htaccess配置文件进行路径修改也可以达到上一条类似的效果,比如

php_value include_path "./include"



在过程中HTML路径的错误需要将其改成根目录下的路径


0 0