Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 510
tslocum Avatar asked Jan 14 '23 04:01

tslocum


1 Answers

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');
like image 184
Rezigned Avatar answered Jan 22 '23 18:01

Rezigned