php 当mkdir从PHP失败时如何找到原因?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/927564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find a reason when mkdir fails from PHP?
提问by Milan Babu?kov
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?
但是,我不喜欢它,因为它使用全局变量。有更清洁的解决方案吗?
回答by soulmerge
You can suppress the warningand make use of error_get_last():
您可以抑制警告并使用error_get_last():
if (!@mkdir($dir)) {
$error = error_get_last();
echo $error['message'];
}
回答by Alistair Evans
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 错误处理程序,那么在 try catch 块之后,只需调用:
restore_error_handler()
回答by nick fox
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);
}

