LoginSignup
1
1

More than 5 years have passed since last update.

PHPでディレクトリを削除

Last updated at Posted at 2017-11-29

scandirやopendirを使う方法等もありますが、globが見易そうでしたのでglobを使って行う方法です。

フレームワーク側に実装されていることもあるので確認することをお勧めします。

/**
 * 指定したディレクトリを削除する
 *
 * @param string $directory_path
 * @return boolean
 */
public function remove_directory(string $directory_path): bool
{
    if ( ! is_dir($directory_path))
    {
        return false;
    }

    foreach (glob($directory_path . '/{*,.[!.]*,..?*}', GLOB_BRACE) as $path)// .と..以外の隠しファイルも対象とする
    {
        if (is_file($path))
        {
            if ( ! unlink($path))
            {
                return false;
            }
        }
        elseif (is_dir($path))
        {
            if ($this->remove_directory($path) === false)
            {
                return false;
            }
        }
    }

    return rmdir($directory_path);
}

globはファイルを検索する際に重宝します。

$txt_file_list = glob('document/*.txt');

exec()でrmコマンドを使った方がワンライナーで実現できるので楽だと思います。コピーに関してもcpコマンドを使った方が同様に楽だと思います。

# 削除
rm -rf name

# コピー
cp -arf source dest

1
1
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
1
1