How to get a platform independent directory separator in PHP?

不问归期 提交于 2019-12-03 05:25:54

问题


I'm building a path string in PHP. I need it to work across platforms (i.e., Linux, Windows, OS X). I'm doing this:

$path = $someDirectory.'/'.$someFile;

Assume $someDirectory and $someFile are formatted correctly at run-time on the various platforms. This works beautifully on Linux and OS X, but not on Windows. The issue is the / character, which I thought would work for Windows.

Is there a PHP function or some other trick to switch this to \ at runtime on Windows?

EDIT: Just to be clear, the resultant string is

c:\Program Files (x86)\Sitefusion\Sitefusion.org\Defaults\pref/user.preferences

on Windows. Obviously the mix of slashes confuses Windows.


回答1:


Try this one

DIRECTORY_SEPARATOR

$patch = $somePath. DIRECTORY_SEPARATOR .$someFile

or you can define yours

PHP_OS == "Windows" ||
    PHP_OS == "WINNT" ? define("SEPARATOR", "\\") : define("SEPARATOR", "/"); 



回答2:


if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')           
    define("SEPARATOR", "\\");
else 
    define("SEPARATOR", "/");

http://php.net/manual/en/function.php-uname.php



来源:https://stackoverflow.com/questions/6654157/how-to-get-a-platform-independent-directory-separator-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!