开发者

How to find symbolic links to the current file?

Is there a way in PHP or Perl to find all s开发者_如何转开发ymbolic links to the current file?


Without traversing the filesystem looking for all symbolic links and then checking their destination, no. But if you still want to do this, it's pretty straight-forward:

use strict;
use warnings;
use File::Find;

my $target = 'the filename you want to find links to';
finddepth(
    sub {
        return if not -l $File::Find::name;
        print "found $File::Find::name!\n" if readlink($File::Find::name) eq $target;
    },
    '/'
);


Not without walking the filesystem or using find (which itself walks the FS). Symlinks aren't actually linked to a file in any meaningful way; they just contain a path to the real file. Those links can be anywhere, and the OS doesn't necessarily know about them at all til they're used in a path.


Not without searching the entire filesystem.

Symlinks (in linux at least) are basically pointers. They point from one location to another, but the location they point to has no way of knowing what points to it without an exhaustive search.

You could do this with a full search, but it could easily take a long time depending on your system.


In PHP you could - in theory - use a RecursiveDirectoryIterator and set it to traverse from the filesystem root. You could then check if the currently iterated filesystem item is a link and if so, use readlink to see where it points to:

$fsi = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator('/'),
    RecursiveIteratorIterator::SELF_FIRST
);
foreach ($fsi as $fso) {
    if ($fso->isLink()) {
        echo readlink($fso->getPathname());
    }
}

In practise, you will likely not be allowed to do that from the user executing the PHP script.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜