你怎么能抓住一个;“拒绝许可”;在PHP中使用fopen而不使用try/catch时出错?

你怎么能抓住一个;“拒绝许可”;在PHP中使用fopen而不使用try/catch时出错?,php,error-handling,fopen,permission-denied,Php,Error Handling,Fopen,Permission Denied,我刚刚收到一个错误报告,因为脚本试图使用“w”(写入)模式打开一个新文件时,出现了一个权限被拒绝的错误。以下是相关功能: function writePage($filename, $contents) { $tempfile = tempnam('res/', TINYIB_BOARD . 'tmp'); /* Create the temporary file */ $fp = fopen($tempfile, 'w'); fwrite($fp, $contents)

我刚刚收到一个错误报告,因为脚本试图使用“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块非常容易,但可移植性是我脚本的一大卖点。我不能牺牲与PHP4的兼容性来处理错误。请帮助我在不打印任何错误/警告的情况下捕获权限错误。

我认为您可以使用此解决方案来防止错误。只需在
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');

虽然我在考虑兼容性,但你究竟为什么要维护PHP4支持?在我能够负担得起付费主机之前,我在许多免费主机之间迁移了。在那段时间里,我了解到许多主机并不急于向用户提供PHP5。在编写脚本时,我的目标之一就是全力支持这样一位主持人。它甚至可以使用平面文件数据库进行操作。如果绝对必要,可以将帖子保存到文件系统,而不是使用MySQL/SQLite。因此,脚本所需的就是PHP4和GD库。当然,从付费主机的角度来看,这是过分的,但是为了支持几乎所有的免费主机,这是必要的。好吧,我赞扬你对向后兼容性的承诺。作为一个建议,也许考虑把你的项目分成一个前/后5.3个分支。