Tilde expansion in PHP

If you have ever written a PHP command line script and tried to pass a file to it using the POSIX tilde (~) shortcut to reference your home directory, you may have been surprised to learn that the operating system does not automatically expand tildes in paths.

You’ll get an error like this:

Warning: fopen(~/file.csv): failed to open stream: No such file or directory

Fortunately, it is an easy matter to perform tilde expansion, once you know you need to.

function expand_tilde($path)
{
    if (function_exists('posix_getuid') && strpos($path, '~') !== false) {
        $info = posix_getpwuid(posix_getuid());
        $path = str_replace('~', $info['dir'], $path);
    }

    return $path;
}

H/T to Ernest Friedman-Hill for cluing me into the solution.

Written on September 3, 2013