使用PHP处理文件时出错

Error Handling with files in PHP

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

Here I want add an error handling by throwing exceptions, on 'No file or directory is found' and 'No permission to create a file'.

I am using Zend Framework.

By using fopen with write mode, I can create a file. But how to handle it when corresponding folder is not there?
i.e if files folder is not present in root structure.

How to throw an exception when no permission is permitted for creating a file?

Something like this should get you started.

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);
}

Then to call

try {
  createFile('path/to/file.csv');
} catch(Exception $e) {
  echo $e->getMessage();
}

I suggest, you take a look at this link: http://www.w3schools.com/php/php_ref_filesystem.asp especially the methods file_exists and is_writable

Like this:

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

PHP will echo whatever error would arise there.


Though you can also use is_dir or is_writable functions to see if folder exists and has permission respectively:

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

But how to handle it when corresponding folder is not there?

When a folder does not exist .. try to create it!

$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!