錯誤與文件處理在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