如果在不使用try / catch的情况下在PHP中使用fopen,如何捕获“权限被拒绝”错误?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了如果在不使用try / catch的情况下在PHP中使用fopen,如何捕获“权限被拒绝”错误?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
当脚本尝试使用“w”(写入)模式打开新文件时,我刚收到有关权限被拒绝错误one of my scripts错误报告.这是相关的功能

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');

脚本宝典总结

以上是脚本宝典为你收集整理的如果在不使用try / catch的情况下在PHP中使用fopen,如何捕获“权限被拒绝”错误?全部内容,希望文章能够帮你解决如果在不使用try / catch的情况下在PHP中使用fopen,如何捕获“权限被拒绝”错误?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。