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

非 Y 不嫁゛ 提交于 2019-12-21 21:53:02

问题


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 */
}

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.


回答1:


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


来源:https://stackoverflow.com/questions/16975998/how-can-you-catch-a-permission-denied-error-when-using-fopen-in-php-without-us

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!