LoginSignup
2
4

More than 3 years have passed since last update.

[PHP]ディレクトリごとファイルをコピーする

Posted at

PHPにはファイルのコピーをするためのcopy関数がありますが、ディレクトリとその中に含まれるファイルを丸ごとコピーすることはできません。
そこで、PHPでディレクトリごとファイルをコピーする方法をご紹介します。

/**
 * ディレクトリをコピーする
 *
 * @param  string $dir     コピー元ディレクトリ
 * @param  string $new_dir コピー先ディレクトリ
 * @return void
 */
function copy_dir($dir, $new_dir)
{
    $dir     = rtrim($dir, '/').'/';
    $new_dir = rtrim($new_dir, '/').'/';

    // コピー元ディレクトリが存在すればコピーを行う
    if (is_dir($dir)) {
        // コピー先ディレクトリが存在しなければ作成する
        if (!is_dir($new_dir)) {
            mkdir($new_dir, DIR_WRITE_MODE);
            chmod($new_dir, DIR_WRITE_MODE);
        }

        // ディレクトリを開く
        if ($handle = opendir($dir)) {
            // ディレクトリ内のファイルを取得する
            while (false !== ($file = readdir($handle))) {
                if ($file === '.' || $file === '..') {
                    continue;
                }
                // 下の階層にディレクトリが存在する場合は再帰処理を行う
                if (is_dir($dir.$file)) {
                    copy_dir($dir.$file, $new_dir.$file);
                } else {
                    copy($dir.$file, $new_dir.$file);
                }
            }
            closedir($handle);
        }
    }
}

こちらの方法で、対象となるディレクトリを丸ごとコピーできます。
さらに下の階層にディレクトリが存在する場合でも、コピーすることが可能です。

2
4
2

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
2
4