[英]How do I check if a directory is writeable in PHP?
是的,它確實適用於文件夾....
如果文件名存在且可寫,則返回 TRUE。 filename 參數可能是一個目錄名,允許您檢查目錄是否可寫。
這是代碼:)
<?php
$newFileName = '/var/www/your/file.txt';
if ( ! is_writable(dirname($newFileName))) {
echo dirname($newFileName) . ' must writable!!!';
} else {
// blah blah blah
}
更具體地針對所有者/組/世界
$dir_writable = substr(sprintf('%o', fileperms($folder)), -4) == "0774" ? "true" : "false";
和平...
您可能正在向is_writable()
函數發送完整的文件路徑。 如果文件不存在於目錄中, is_writable()
將返回 false。 如果是這種情況,您需要檢查刪除了文件名的目錄本身。 如果你這樣做, is_writable
會正確地告訴你目錄是否可寫。 如果$file
包含您的文件路徑,請執行以下操作:
$file_directory = dirname($file);
然后使用is_writable($file_directory)
確定文件夾是否可寫。
我希望這可以幫助別人。
根據is_writable 的文檔,它應該可以正常工作-但是您說的是“文件夾”,因此這可能是Windows 問題。 評論提出了一種解決方法。
(早些時候匆忙閱讀讓我認為尾部斜杠很重要,但結果證明這是特定於這項工作的)。
我編寫了一個小腳本(我稱之為isWritable.php ),它檢測腳本所在目錄中的所有目錄,並將每個目錄是否可寫寫入頁面。 希望這可以幫助。
<?php
// isWritable.php detects all directories in the same directory the script is in
// and writes to the page whether each directory is writable or not.
$dirs = array_filter(glob('*'), 'is_dir');
foreach ($dirs as $dir) {
if (is_writable($dir)) {
echo $dir.' is writable.<br>';
} else {
echo $dir.' is not writable. Permissions may have to be adjusted.<br>';
}
}
?>
根據 PHP 手冊is_writable應該可以在目錄上正常工作。
在我的情況下, is_writable
返回 true,但是當嘗試寫入文件時 - 生成了錯誤。
此代碼有助於檢查$dir
存在且是否可寫:
<?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);
}
}
這就是我的做法:
使用file_put_contents()
創建一個文件並檢查返回值,如果它是正的(以字節為單位寫入的數量)那么你可以繼續做你必須做的事情,如果它是 FALSE 那么它是不可寫的
$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";
然后您可以使用 unlink() 刪除虛擬文件
unlink('directory/dummy.txt');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.