在PHP中,如何以操作系统友好的方式引用文件?我正在看一些类似的代码
<?php
require_once(dirname(dirname(__FILE__)).'/common/config.inc.php');
...
Run Code Online (Sandbox Code Playgroud)
我必须在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
Run Code Online (Sandbox Code Playgroud)
看起来它正试图打开窗户不喜欢的正斜杠.文件C:\ workspace\commonconfig.inc.php存在.该脚本只是找不到它,因为它有正斜杠吗?
在require_once语句中,我不应该以某种os友好的方式表达路径的最后部分吗?你是怎样做的?
在PHP中,是否有类似于Python的 os.path.normpath(path)?..which采用类似路径的字符串并返回适合正在运行的OS的路径...
你可以使用一些东西.
而不是硬编码斜杠,使用内置常量DIRECTORY_SEPARATOR,或者根据我的喜好,制作自己的:
define('DS', DIRECTORY_SEPARATOR);
Run Code Online (Sandbox Code Playgroud)
..使你的代码更紧凑.
或者,使用realpath()并使用unix样式正斜杠表达所有路径,因为:
在Windows上,realpath()会将unix样式路径更改为windows样式.
<?php echo realpath('/windows/system32'); ?>上面的例子将输出:
C:\WINDOWS\System32