PHP imap_reopen 没有返回错误

PHP imap_reopen no error returned

我有一个连接到邮箱的脚本。 我想检查我是否可以连接到一个不存在的文件夹,但是 imap_reopen 没有 return 错误。

<?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

你有想法吗?

此致,

斯蒂蒂

您以 or die() 结尾的语句实际上是在针对 $test 中的 return 值进行 if 测试之前终止执行。

$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) 就会被计算。我也会在这里使用 === 因为它应该 return 一个真正的布尔值:

// 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() 即使在 returning 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() 是苗条和模棱两可的,说明其 return 为:

Returns TRUE if the stream is reopened, FALSE otherwise.

一些测试似乎暗示打开一个不存在的邮箱不被视为错误状态 returns false。当在其他有效流上打开不存在的邮箱时,imap_reopen() 仍将 return true 但会在 imap_errors().

中填充错误

因此您可以在打开故障邮箱后检查count(imap_errors()) > 0是否有错误。将其与 true return 检查相结合,以防 imap_reopen() 确实 return 真正的错误状态。

例如,我的测试产生的结果类似于:

$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>.