Skip to content

Instantly share code, notes, and snippets.

Created November 20, 2017 14:24
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
PHP logicalpath()
function logicalpath($path) {
// same as realpath() except keeps logical paths
if (!file_exists($path)) {
return False;
$filename = '';
if (is_file($path)) {
$filename = (basename($path));
$length = strlen($filename);
$path = substr($path, 0, -$length);
$filename = '/'.$filename;
return exec('bash -c "cd '. escapeshellarg($path) .' && pwd -L"').$filename;
Copy link

markclowes commented Nov 20, 2017

I recently needed to be able to resolve the real logical path, similar to realpath() but leaving symlinks intact. I couldn't find an elegant way to do this without shelling out unfortunately. As far as I am aware it is functionally equivalent to realpath().

mac@localhost:~$ mkdir foo
mac@localhost:~$ mkdir bar
mac@localhost:~$ ln -s ../bar foo/
mac@localhost:~$ touch ~/foo/bar/xyzzy.txt
mac@localhost:~$ cd foo/bar
mac@localhost:~/foo/bar$ pwd -L
mac@localhost:~/foo/bar$ pwd -P
mac@localhost:~/foo/bar$ php -a
Interactive mode enabled

php > include '/home/mac/paths.php';
php > echo(realpath('/home/mac/foo/bar/'));
php > echo(logicalpath('/home/mac/foo/bar/'));
php > echo(logicalpath('/var/tmp/../../home/mac/foo/bar/'));
php > echo(logicalpath('/var/tmp/../../home/mac/foo/bar/xyzzy.txt'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment