LoginSignup
9
9

More than 5 years have passed since last update.

ファイル作成時に途中のディレクトリが存在しなくても作成してくれるメソッド

Posted at

あるファイルを作成したいといった場合に、素直にtouchなんかでファイルを作成したくても途中のディレクトリが存在しないためエラーになってしまうということがあったりします。
なので、パスに含まれるディレクトリの存在をチェックし、無ければ合わせてそのディレクトリも作成するメソッドを作ってみました。

ファイルまたはディレクトリの両方を作成できますが、ディレクトリを作成したい場合は引数のパスの最後に/をつける必要があります。
/path/to/barならbarファイルができますが、/path/to/bar/ならbarディレクトリを作成します。

function createFile($file)
{
    // ファイルが既に存在する場合
    if (!empty($file) && is_readable($file)) {
        return true;
    } else {
        // 最後がスラッシュで終わる場合
        if (substr($file, -1) === '/') {
            return mkdir($file, 0777, true);
        } else {
            $path = pathinfo($file);
            // ディレクトリがあればファイルだけ作成、無ければディレクトリ+ファイルを作成
            return is_readable($path['dirname']) ? touch($file) : (mkdir($path['dirname'], 0777, true) && touch($file));
        }
    }
}
9
9
1

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