How can I define the DIRECTORY_SEPARATOR for both

2020-02-19 03:20发布

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\index but in Linux /www/app/index so when I define the path using this / but when the application run in window machine it should be problem for this /.

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

5条回答
祖国的老花朵
2楼-- · 2020-02-19 03:24

Please see PHP Predefined Constants

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

查看更多
干净又极端
3楼-- · 2020-02-19 03:27

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

查看更多
太酷不给撩
4楼-- · 2020-02-19 03:28

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

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

Example:

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

echo dosPath($drive.$path);
echo dosPath($path);
查看更多
对你真心纯属浪费
5楼-- · 2020-02-19 03:32

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?

查看更多
姐就是有狂的资本
6楼-- · 2020-02-19 03:46

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

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

查看更多
登录 后发表回答