代码之家  ›  专栏  ›  技术社区  ›  Purrell

如何以操作系统友好的方式引用本地路径?

php
  •  1
  • Purrell  · 技术社区  · 16 年前

    在PHP中,如何以操作系统友好的方式引用文件?我在看一些代码,比如

    <?php
    require_once(dirname(dirname(__FILE__)).'/common/config.inc.php');
    
    ...
    

    我必须在Windows计算机上运行,但它不能正确解析路径:

    PHP Warning:  require_once(C:\workspace/common/config.inc.php): failed to open stream: No such file or directory in C:\workspace\somescript.php on line 2
    PHP Fatal error:  require_once(): Failed opening required 'C:\workspace/common/config.inc.php' (include_path='.;C:\php5\pear') in C:\workspace\somescript.php on line 2
    

    它似乎试图用窗户不喜欢的正斜杠打开。文件C:\workspace\commonconfig.inc.php存在。剧本就是找不到它,因为它有正斜杠,对吧?

    os.path.normpath(path)

    3 回复  |  直到 16 年前
        1
  •  8
  •   nickf    16 年前

    有几样东西你可以用。

    使用内置常量而不是硬编码斜线 DIRECTORY_SEPARATOR

    define('DS', DIRECTORY_SEPARATOR);
    

    ..它使您的代码更加紧凑。

    realpath() 并用unix风格的正斜杠表示所有路径,因为:

    在windows上,realpath()将把unix样式的路径更改为windows样式。
    <?php echo realpath('/windows/system32'); ?>

    上述示例将输出: C:\WINDOWS\System32

        2
  •  2
  •   hlpiii    16 年前
    require_once(realpath)(目录名(__FILE__)。“/the/rest/of/yr/path/和/file.php”);
    
        3
  •  2
  •   cletus    16 年前

    我这样做:

    $dir = str_replace("\\", '/', dirname(dirname(__FILE__));
    require_once $dir . '/common/config.inc.php';
    

    require_once '../common/config.inc.php';
    

    ?

    推荐文章