LoginSignup
4
3

More than 5 years have passed since last update.

ディレクトリを作るイディオム

Posted at

書き込み先のディレクトリが存在しなければ、file_put_contentsE_WARNINGを発生させます。そして、ディレクトリを作ってくれません。

e_warning.php
<?
error_reporting(E_ALL);
file_put_contents('sandbox/foo.php', '// うまく書き込めない。');

そこで、必要に応じてディレクトリを作成するようなスニペットを書きました。

digg.php
<?
error_reporting(E_ALL);
$filename = 'sandbox/deep/deep/foo.php';
$paths = explode('/', $filename);
$basename = array_pop($paths);
if (count($paths) > 0) {
    $dir = implode('/', $paths);
    is_dir($dir) or mkdir($dir, 0777, true);
}
file_put_contents($filename, "// 無事ファイルに書き込みできる");

これで、E_WARNINGを発生させずに、ディレクトリを作ることができます:star:

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