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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With