How do I check if a directory is writeable in PHP?

Viewed 83228

Does anyone know how I can check to see if a directory is writeable in PHP?

The function is_writable doesn't work for folders.

Edit: It does work. See the accepted answer.

10 Answers

Yes, it does work for folders....

Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable.

stat()

Much like a system stat, but in PHP. What you want to check is the mode value, much like you would out of any other call to stat in other languages (I.E. C/C++).

http://us2.php.net/stat

According to the PHP manual is_writable should work fine on directories.

In my case, is_writable returned true, but when tried to write the file - an error was generated.
This code helps to check if the $dir exists and is writable:

<?php
$dir = '/path/to/the/dir';

// try to create this directory if it doesn't exist
$booExists     = is_dir($dir) || (mkdir($dir, 0774, true) && is_dir($dir));
$booIsWritable = false;
if ($booExists && is_writable($dir)) {
    $tempFile = tempnam($dir, 'tmp');
    if ($tempFile !== false) {
        $res = file_put_contents($tempFile, 'test');

        $booIsWritable = $res !== false;
        @unlink($tempFile);
    }
}
Related