Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding broken symlinks using php

Tags:

php

symlink

glob

I'm writing a build/deploy script using a CLI php script.

Say I have a directory /environment and in it there are simply two broken symlinks.

I'm running glob(/environment/{,.}*). When I foreach over the glob, all I see are . and ... The symlinks never show up in the list.

How can you loop over a directory, detect broken symlinks, and unlink() them using PHP?

like image 957
Rimer Avatar asked Sep 01 '25 02:09

Rimer


1 Answers

On a broken symlink is_link() returns true and file_exists() returns false.

Since glob() does not list broken symlinks, you have to list the contents in a different way. Here is an example using scandir()

   foreach(scandir($dir) as $entry) {
        $path = $dir . DIRECTORY_SEPARATOR . $entry;
        if (is_link($path) && !file_exists($path)) {
            @unlink($path);
        }
    }
like image 188
Luigi Belli Avatar answered Sep 02 '25 14:09

Luigi Belli