错误与文件处理在PHP错误与文件处理在PHP
$path = '/home/test/files/test.csv';
fopen($path, 'w')
在这里,我想通过抛出异常增加一个错误处理,在“无文件或目录被发现”和“禁止创建一个文件”。
我正在使用Zend Framework。
通过使用fopen与编写模式,我可以创建一个文件。但如何处理它时,相应的文件夹不存在?
即,如果files
文件夹不存在于根结构中。
如何在创建文件不允许权限时抛出异常?
错误与文件处理在PHP错误与文件处理在PHP
$path = '/home/test/files/test.csv';
fopen($path, 'w')
在这里,我想通过抛出异常增加一个错误处理,在“无文件或目录被发现”和“禁止创建一个文件”。
我正在使用Zend Framework。
通过使用fopen与编写模式,我可以创建一个文件。但如何处理它时,相应的文件夹不存在?
即,如果files
文件夹不存在于根结构中。
如何在创建文件不允许权限时抛出异常?
像这样的东西应该让你开始。
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();
}
我建议,你看看这个链接:http://www.w3schools.com/php/php_ref_filesystem.asp 特别是方法file_exists
和is_writable
像这样:
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...
但如何处理它时,对应的文件夹,不是吗?
当一个文件夹不存在..尝试创建它!
$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!
此异常是否可以在SSH中使用? – 2012-07-12 11:01:54
'fopen()'不会抛出异常;它会产生错误。所以try/catch不会做任何事情。 – 2012-07-12 11:04:55