10
15

More than 5 years have passed since last update.

空でないディレクトリを削除する

Posted at

glob() を使ってディレクトリ配下のパスを収集。

再帰関数版

rmrf.php
<?php

function rmrf($dir) {
    if (is_dir($dir) and !is_link($dir)) {
        array_map('rmrf',   glob($dir.'/*', GLOB_ONLYDIR));
        array_map('unlink', glob($dir.'/*'));
        rmdir($dir);
    }
}

$dir = "aaa";
rmrf($dir);

インライン版

rmdir_r.php
<?php

$dir = "aaa";

if (is_dir($dir) and !is_link($dir)) {
    $paths = array();
    while ($glob = glob($dir)) {
        $paths = array_merge($glob, $paths);
        $dir .= '/*';
    }
    array_map('unlink', array_filter($paths, 'is_file'));
    array_map('rmdir',  array_filter($paths, 'is_dir'));
}

隠しファイルやディレクトリへのシンボリックリンクが含まれていると失敗する…

10
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
15