file_exists() returns false when using path with ~, tilde in it

前端 未结 2 608
无人及你
无人及你 2021-01-20 08:17

So I have the following path: /my_user/path/to/dir, and when I pass it to file_exists(), it works fine.

However, when I change it to

相关标签:
2条回答
  • 2021-01-20 08:55
    $home_dir = exec( 'echo ~' ) ;
    
    0 讨论(0)
  • 2021-01-20 08:58

    Tilde expansion is a shell feature, so its use outside the context of a shell (or another program in which the developer has chosen to implement this shell feature) is not possible, as it is not intrinsic to the filesystem or any other part of the OS.

    The behaviour is defined in section 2.6.1 of the POSIX specification. The introduction to that chapter states:

    The shell is a command language interpreter. This chapter describes the syntax of that command language as it is used by the sh utility and the system() and popen() functions defined in the System Interfaces volume of POSIX.1-2017.


    If you want to use such a filename, you can use some of PHP's built-in functions to expand it:

    <?php
    $dir = "~username/bar/baz/";
    $dirparts = explode("/", $dir);
    array_walk(
        $dirparts,
        function(&$v, $k) {
            if ($v[0] ?? "" === "~") $v = posix_getpwnam(substr($v, 1))["dir"] ?? $v;
        }
    );
    $expanded = implode("/", $dirparts);
    echo $expanded;
    
    0 讨论(0)
提交回复
热议问题