问题描述
我刚刚收到有关许可的其中一个脚本的错误报告当脚本尝试使用"w"(写入)模式打开新文件时,拒绝错误.这是相关的功能:
I just received an error report for one of my scripts regarding a permission denied error when the script tries to open a new file using 'w' (writing) mode. Here's the relevant function:
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的兼容性来处理错误.请帮助我捕获权限错误,而不打印任何错误/警告.
You can see the third line is where I am using fopen. I would like to catch permission denied errors and handle them myself rather than print an error message. I realize this is very easy using a try/catch block, but portability is a large selling point for my script. I can't sacrifice compatibility with PHP 4 to handle an error. Please help me catch a permission error without printing any errors/warnings.
推荐答案
我认为您可以通过使用此解决方案来防止出现此错误.只需在tempnam
行之后添加额外的支票
I think you can prevent the error by using this solution. Just add an extra check after tempnam
line
$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');
这篇关于您如何才能捕获到“权限被拒绝"消息?在PHP中使用fopen而不使用try/catch时出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!