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

2019-02-05 10:30发布

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.)

9条回答
你好瞎i
2楼-- · 2019-02-05 10:44

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-02-05 10:47

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).

查看更多
该账号已被封号
4楼-- · 2019-02-05 10:48

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.

查看更多
放荡不羁爱自由
5楼-- · 2019-02-05 10:49

to be more specific for owner/group/world

$dir_writable = substr(sprintf('%o', fileperms($folder)), -4) == "0774" ? "true" : "false";

peace...

查看更多
Evening l夕情丶
6楼-- · 2019-02-05 10:49

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');
查看更多
虎瘦雄心在
7楼-- · 2019-02-05 10:54

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

查看更多
登录 后发表回答