如何为 Windows 和 Linux 平台定义 DIRECTORY_SEPARATOR?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6619020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:59:38  来源:igfitidea点击:

How can I define the DIRECTORY_SEPARATOR for both Windows and Linux platforms?

phpwindowslinux

提问by useCase

Now I create a small PHP Application, here I have problem for using file path, because in Windows use this type location C:\Some\Location\indexbut in Linux /www/app/indexso when I define the path using this /but when the application run in window machine it should be problem for this /.

现在我创建了一个小的 PHP 应用程序,在这里我有使用文件路径的问题,因为在 Windows 中使用这种类型的位置,C:\Some\Location\index但是Linux /www/app/index当我使用它定义路径/时,但是当应用程序在窗口机器中运行时,这应该是问题/

So here I want to define the DIRECTORY_SEPARATOR both Windows and Linux platform.

所以在这里我想定义 Windows 和 Linux 平台的 DIRECTORY_SEPARATOR。

采纳答案by zerkms

PHP accepts both \and /as valid path separators in all OS. So just use /in your code

PHP 接受\/作为所有操作系统中的有效路径分隔符。所以只需/在您的代码中使用

回答by Neverever

Please see PHP Predefined Constants

请参阅PHP 预定义常量

Maybe it's already defined in your script, try echoing DIRECTORY_SEPARATOR, see if it has any value

也许它已经在你的脚本中定义了,尝试回显 DIRECTORY_SEPARATOR,看看它是否有任何价值

回答by shelhamer

For convenience you can write define a shorter constant:

为方便起见,您可以编写定义一个较短的常量:

DEFINE('DS', DIRECTORY_SEPARATOR); 

and then write your path as:

然后将您的路径写为:

$path = 'www'.DS.'app'.DS.'index'; 

Or do I not understand your question?

还是我不明白你的问题?

回答by Hans Kerkhof

PHP understands '\' and '/' as path separators, regardless on the system you're on. I prefer to use '/' (the unix way) in all of my code. When you're on a windows box and there is a need to provide a full qualified windows/DOS path I'll have this simple, non destructive function

PHP 将 '\' 和 '/' 理解为路径分隔符,无论您在哪个系统上。我更喜欢在我的所有代码中使用“/”(unix 方式)。当你在一个 windows 机器上并且需要提供一个完全合格的 windows/DOS 路径时,我将拥有这个简单的、非破坏性的功能

function dosPath($path){
    return str_replace('/', '\', $path);
}

Example:

例子:

$drive = 'C:';
$path = '/tmp/uploads';

echo dosPath($drive.$path);
echo dosPath($path);

回答by MarkR

Windows accepts forward slashes in most cases, so you can just use those. You can even use a mixture and it won't complain.

在大多数情况下,Windows 接受正斜杠,因此您可以使用它们。你甚至可以使用混合物,它不会抱怨。

Make sure that your unit-test suite passes on Linux as well though!

确保您的单元测试套件也通过 Linux!

回答by Junaid

Try this for window

试试这个窗口

defined ('DS') ? null : define('DS', DIRECTORY_SEPARATOR);

define( 'SITE_ROOT',  DS . 'xampp' . DS .'htdocs' .  DS .'gallery');