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

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

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

    在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存在。脚本只是找不到它,因为它有正斜杠对吗?

    在require-once语句中,我不应该以某种操作系统友好的方式表达路径的最后一部分吗?你是怎么做到的?

    在PHP中,是否有类似于Python的 os.path.normpath(path) ?…它采用类似于字符串的路径,并返回适合正在运行的操作系统的路径…

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

    你可以用一些东西。

    不要硬编码斜线,而是使用内置常量 DIRECTORY_SEPARATOR 或者我更喜欢,自己做:

    define('DS', DIRECTORY_SEPARATOR);
    

    …它使代码更加紧凑。

    或者,使用 realpath() 并使用Unix样式的正斜杠表示所有路径,因为:

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

    上面的示例将输出: C:\WINDOWS\System32

        2
  •  2
  •   hlpiii    15 年前
    需要一次(realpath(dirname(uuu file_uuu))。//rest/of/yr/path/和/file.php”);
    
        3
  •  2
  •   cletus    15 年前

    我这样做:

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

    适用于Windows和Linux。虽然在这种情况下,为什么不只是这样做:

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

    ?