PHP's mkdir function only returns true and false. Problem is when it returns false.
PHP的mkdir函数只返回true和false。问题是它何时返回false。
If I'm running with error reporting enabled, I see the error message on the screen. I can also see the error message in the Apache log. But I'd like to grab the text of the message and do something else with it (ex. send to myself via IM). How do I get the error text?
如果我在启用错误报告的情况下运行,我会在屏幕上看到错误消息。我还可以在Apache日志中看到错误消息。但是我想抓住消息的文本并用它做其他事情(例如通过IM发送给我自己)。如何获取错误文本?
Update: Following Ayman's idea, I came to this:
更新:遵循艾曼的想法,我来到这里:
function error_handler($errno, $errstr) {
global $last_error;
$last_error = $errstr;
}
set_error_handler('error_handler');
if (!mkdir('/somedir'))
echo "MKDIR failed, reason: $last_error\n";
restore_error_handler();
However, I don't like it because it uses global variable. Any idea for a cleaner solution?
但是,我不喜欢它,因为它使用全局变量。想要更清洁的解决方案吗?
3 个解决方案
#1
48
You can suppress the warning and make use of error_get_last()
:
您可以禁止警告并使用error_get_last():
if (!@mkdir($dir)) {
$error = error_get_last();
echo $error['message'];
}
#2
14
You could use exceptions:
你可以使用例外:
Setup some code like so:
设置一些代码如下:
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
And then just do:
然后就是:
try {
mkdir('/somedir');
} catch(ErrorException $ex) {
echo "Error: " . $ex->getMessage();
}
That should do what you want.
那应该做你想要的。
If you want to preserve the php error handler, then after that try catch block, just call:
如果你想保留php错误处理程序,那么在尝试catch块之后,只需调用:
restore_error_handler()
#3
3
I use something like the following:
我用的东西如下:
if(! @mkdir('$fileLocation', 0777, $recursive = true)){
$mkdirErrorArray = error_get_last();
throw new Exception('cant create directory ' .$mkdirErrorArray['message'], 1);
}
#1
48
You can suppress the warning and make use of error_get_last()
:
您可以禁止警告并使用error_get_last():
if (!@mkdir($dir)) {
$error = error_get_last();
echo $error['message'];
}
#2
14
You could use exceptions:
你可以使用例外:
Setup some code like so:
设置一些代码如下:
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
And then just do:
然后就是:
try {
mkdir('/somedir');
} catch(ErrorException $ex) {
echo "Error: " . $ex->getMessage();
}
That should do what you want.
那应该做你想要的。
If you want to preserve the php error handler, then after that try catch block, just call:
如果你想保留php错误处理程序,那么在尝试catch块之后,只需调用:
restore_error_handler()
#3
3
I use something like the following:
我用的东西如下:
if(! @mkdir('$fileLocation', 0777, $recursive = true)){
$mkdirErrorArray = error_get_last();
throw new Exception('cant create directory ' .$mkdirErrorArray['message'], 1);
}