开发者

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

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 shou开发者_运维技巧ld be problem for this /.

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


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


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?


Please see PHP Predefined Constants

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


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);


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!


Try this for window

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

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


This is messy, would you agree?

$file = 'path' . DIRECTORY_SEPARATOR . 'to' . DIRECTORY_SEPARATOR . 'file';

$file = str_replace('/', DIRECTORY_SEPARATOR, 'path/to/file';

$file = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? 'path\\to\\file' : 'path/to/file';

So just do this:

$file = 'path/to/file';

It works on Windows, Linux, Mac altogether. Backslash however only works on Windows and needs to be escaped \\ so try to avoid them. :)

To turn a file referenced by PHP on Windows into forward slahes, use str_replace. Here is an example:

$dir = str_replace('\\', '/', realpath('../'));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜