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 ~username/path/to/dir
, it returns false.
realpath("~username/path/to/dir")
returns false as well.
What can be wrong?
Note: This is not a duplicate of How to get the home directory from a PHP CLI script? because I'm more curious about why the tilde doesn't work, rather than how to work around it.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With