我有一个连接到邮箱的脚本。
我想检查一下我是否可以连接到不存在的文件夹,但imap_reopen
不会返回错误。
<?php
$imap_url = "{mybox.mail.box:143}";
$mbox = imap_open($imap_url, "Mylogin", "Mypassword");
if ($mbox == false) {
echo "Opening mailbox failed\n";
}
$submbox = imap_listmailbox($mbox, $imap_url, "*");
if ($submbox == false) {
echo "Listing sub-mailboxes failed\n";
}
else {
foreach ($submbox as $name) {
echo $name . PHP_EOL;
}
}
$test = imap_reopen($mbox, $imap_url . "INBOX.MBOX3") or die(implode(", ", imap_errors()));
if ($test == false) {
echo "Opening submbox failed\n";
}
?>
脚本输出:
{mybox.mail.box:143}.INBOX
{mybox.mail.box:143}.INBOX.MBOX1
{mybox.mail.box:143}.INBOX.MBOX2
PHP Notice: Unknown: Mailbox does not exist (errflg=2) in Unknown on line 0
你有什么想法吗?
此致
Stiti
答案 0 :(得分:2)
以or die()
结尾的语句实际上是在针对if
中的返回值的$test
测试之前终止执行。
$test = imap_reopen($mbox, $imap_url . "INBOX.MBOX3") or die(implode(", ", imap_errors()));
// This code is never reached because of die()!
if ($test == false) {
echo "Opening submbox failed\n";
}
因此,只需删除or die()
表达式,即可评估if ($test == false)
。我也会在这里使用===
因为它应该返回一个真正的布尔值:
// Call imap_reopen() without (or die())
$test = imap_reopen($mbox, $imap_url . "INBOX.MBOX3");
if ($test === false) {
echo "Opening submbox failed\n";
}
您也可以使用
if (!$test) {
echo "Opening submbox failed\n";
}
注意发出的PHP E_NOTICE - 如果imap_reopen()
即使在返回false
时发出通知,这也是您可能希望使用@
运算符进行错误抑制的一个实例您正在针对if
块中的错误进行正确测试。
// @ is not usually recommended but if imap_reopen()
// prints an E_NOTICE while still returning false you can
// suppress it with @. This is among the only times it's
// a good idea to use @ for error suppresssion
$test = @imap_reopen($mbox, $imap_url . "INBOX.MBOX3");
if (!$test) {...}
Documentation on imap_reopen()
渺茫而含糊不清地表示其回归:
如果重新打开流,则返回TRUE,否则返回FALSE。
某些测试似乎暗示打开一个不存在的邮箱不会被视为一个错误状态,它将返回false
。在其他有效的流上打开不存在的邮箱时,imap_reopen()
仍会返回true
,但会在imap_errors()
中填充错误。
因此,您可以在打开故障邮箱后检查count(imap_errors()) > 0
是否有错误。如果true
确实返回真正的错误状态,那么请使用imap_reopen()
返回检查。
例如,我的测试产生的结果类似于:
$test = imap_reopen($mbox, $imap_url . "NOTEXIST");
var_dump($test);
// bool(true);
var_dump(imap_errors()); array(1) {
[0] =>
string(28) "Mailbox doesn't exist: NOTEXIST"
}
您可以使用逻辑解决此问题:
$test = @imap_reopen($mbox, $imap_url . "INBOX.MBOX3");
if (!$test) {
// An error with the stream
}
// Returns true, but imap_errors() is populated
else if ($test && count(imap_errors()) > 0) {
echo "Opening submbox failed\n";
// Do something with imap_errors() if needed
echo implode(',', imap_errors());
}
else {
// Everything is fine - the mailbox was opened
}
对于它的价值,imap_open()
表现出相同的行为。使用不存在的邮箱可以成功连接和建立流(您的变量$mbox
)。该流已创建且有效,但imap_errors()
将包含消息Mailbox doesn't exist: <mailbox>
。