Reputation: 2074
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?
Upvotes: 4
Views: 2166
Reputation: 664
use realpath
function:
foreach(scandir($dir) as $entry) {
$path = $dir . DIRECTORY_SEPARATOR . $entry;
if (!realpath($path)) {
@unlink($path);
}
}
Upvotes: 0
Reputation: 597
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);
}
}
Upvotes: 8