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 doe
According to the PHP manual is_writable should work fine on directories.
this is how I do it:
create a file with file_put_contents()
and check the return value, if it is positive (number of written in Bytes) then you can go ahead and do what you have to do, if it is FALSE then it is not writable
$is_writable = file_put_contents('directory/dummy.txt', "hello");
if ($is_writable > 0) echo "yes directory it is writable";
else echo "NO directory it is not writable";
then you can delete the dummy file by using unlink()
unlink('directory/dummy.txt');
According to the documentation for is_writable, it should just work - but you said "folder", so this could be a Windows issue. The comments suggest a workaround.
(A rushed reading earlier made me think that trailing slashes were important, but that turned out to be specific to this work around).
to be more specific for owner/group/world
$dir_writable = substr(sprintf('%o', fileperms($folder)), -4) == "0774" ? "true" : "false";
peace...
You may be sending a complete file path to the is_writable()
function. is_writable()
will return false if the file doesn't already exist in the directory. You need to check the directory itself with the filename removed, if this is the case. If you do that, is_writable
will correctly tell you whether the directory is writable or not. If $file
contains your file path do this:
$file_directory = dirname($file);
Then use is_writable($file_directory)
to determine if the folder is writable.
I hope this helps someone.
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);
}
}