【问题标题】:How can you catch a "permission denied" error when using fopen in PHP without using try/catch?在 PHP 中使用 fopen 而不使用 try/catch 时,如何捕获“权限被拒绝”错误?
【发布时间】:2013-06-07 03:59:22
【问题描述】:

我刚刚收到one of my scripts 的错误报告,内容是当脚本尝试使用“w”(写入)模式打开新文件时出现权限被拒绝错误。下面是相关函数:

function writePage($filename, $contents) {
    $tempfile = tempnam('res/', TINYIB_BOARD . 'tmp'); /* Create the temporary file */
    $fp = fopen($tempfile, 'w');
    fwrite($fp, $contents);
    fclose($fp);
    /* If we aren't able to use the rename function, try the alternate method */
    if (!@rename($tempfile, $filename)) {
        copy($tempfile, $filename);
        unlink($tempfile);
    }

    chmod($filename, 0664); /* it was created 0600 */
}

你可以看到第三行是我使用 fopen 的地方。我想捕获权限被拒绝的错误并自己处理它们,而不是打印错误消息。我意识到这很容易使用 try/catch 块,但可移植性是我脚本的一大卖点。我不能牺牲与 PHP 4 的兼容性来处理错误。请帮助我在不打印任何错误/警告的情况下捕获权限错误。

【问题讨论】:

  • 虽然我是为了兼容性,但你到底为什么要维护 PHP 4 支持?
  • 在我负担得起付费主机之前,我在许多免费主机之间迁移。在那段时间里,我了解到这些主机中的许多并不急于向他们的用户提供 PHP 5。在编写脚本时,我的一个目标是完全支持这样的主机。它甚至可以使用平面文件数据库进行操作。如果绝对必要,可以将帖子保存到文件系统而不是使用 MySQL/SQLite。因此,该脚本只需要 PHP 4 和 GD 库。从付费托管的角度来看,这确实有点矫枉过正,但为了支持几乎所有免费主机,这是必要的。
  • 嗯,我赞赏您对向后兼容性的承诺。作为建议,或许可以考虑将您的项目分叉到 5.3 之前/之后的分支中。

标签: php error-handling fopen permission-denied


【解决方案1】:

我认为您可以通过使用此解决方案来防止错误。只需在tempnam 行之后添加一个额外的检查

$tempfile = tempnam('res/', TINYIB_BOARD . 'tmp'); 

# Since we get the actual file name we can check to see if it is writable or not
if (!is_writable($tempfile)) {
    # your logic to log the errors

    return;
}

/* Create the temporary file */
$fp = fopen($tempfile, 'w');

【讨论】:

    猜你喜欢
    • 2020-09-30
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 2013-07-30
    • 2012-02-11
    • 2011-11-10
    • 1970-01-01
    相关资源
    最近更新 更多