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_diroris_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 回答