Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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.

like image 663
tera_789 Avatar asked Sep 20 '25 05:09

tera_789


1 Answers

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;
like image 131
miken32 Avatar answered Sep 22 '25 08:09

miken32