0

PHP でのファイルのエラー処理

$path = '/home/test/files/test.csv';
fopen($path, 'w')

ここで、「ファイルまたはディレクトリが見つかりません」および「ファイルを作成する権限がありません」という例外をスローして、エラー処理を追加します。

Zend フレームワークを使用しています。

書き込みモードでfopenを使用すると、ファイルを作成できます。しかし、対応するフォルダがない場合の処理​​方法は? つまり、フォルダーがルート構造に存在しない場合。
files

ファイルを作成する権限が許可されていない場合に例外をスローする方法は?

4

4 に答える 4

3

このような何かがあなたを始めさせるはずです。

function createFile($filePath)
{
  $basePath = dirname($filePath);
  if (!is_dir($basePath)) {
    throw new Exception($basePath.' is an existing directory');
  }
  if (!is_writeable($filePath) {
    throw new Exception('can not write file to '.$filePath);
  }
  touch($filePath);
}

それから電話する

try {
  createFile('path/to/file.csv');
} catch(Exception $e) {
  echo $e->getMessage();
}
于 2012-07-12T11:03:10.050 に答える
0

このリンクをご覧になることをお勧めします: http://www.w3schools.com/php/php_ref_filesystem.asp 特にメソッドfile_existsis_writable

于 2012-07-12T10:53:33.653 に答える
0

このような:

try
{
  $path = '/home/test/files/test.csv';
  fopen($path, 'w')
}
catch (Exception $e)
{
  echo $e;
}

PHPは、そこで発生するecho エラーをすべて処理します。


is_dirまたはis_writable関数を使用して、フォルダーが存在し、それぞれ権限があるかどうかを確認することもできますが、

is_dir(dirname($path)) or die('folder doesnt exist');
is_writable(dirname($path)) or die('folder doesnt have write permission set');
// your rest of the code here now...
于 2012-07-12T10:53:54.390 に答える
0

しかし、対応するフォルダがない場合の処理​​方法は?

フォルダが存在しない場合..作成してみてください!

$dir = dirname($file);
if (!is_dir($dir)) {
    if (false === @mkdir($dir, 0777, true)) {
        throw new \RuntimeException(sprintf('Unable to create the %s directory', $dir));
    }
} elseif (!is_writable($dir)) {
    throw new \RuntimeException(sprintf('Unable to write in the %s directory', $dir));
}

// ... using file_put_contents!
于 2012-07-12T11:15:33.670 に答える