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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>