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
$home_dir = exec( 'echo ~' ) ;
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 thesystem()
andpopen()
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;