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


How can you catch a "permission denied" error when using fopen in PHP without using try/catch?

我刚刚收到一个关于权限拒绝错误的脚本报告,当脚本试图使用'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的兼容性。请帮助我捕获权限错误,而不打印任何错误/警告

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