代码之家  ›  专栏  ›  技术社区  ›  SeanDowney

如何检查目录在PHP中是否可写?

  •  55
  • SeanDowney  · 技术社区  · 18 年前

    功能 is_writable 不适用于文件夹。

    9 回复  |  直到 6 年前
        1
  •  98
  •   DGM    18 年前

    是的,它确实适用于文件夹。。。。

    如果文件名存在且可写,则返回TRUE。filename参数可能是一个目录名,允许您检查目录是否可写。

        2
  •  23
  •   Irfan EVRENS    11 年前

    <?php 
    
    $newFileName = '/var/www/your/file.txt';
    
    if ( ! is_writable(dirname($newFileName))) {
    
        echo dirname($newFileName) . ' must writable!!!';
    } else {
    
        // blah blah blah
    }
    
        3
  •  6
  •   Griffith    15 年前

    对所有者/集团/世界更具体

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

    和平

        4
  •  5
  •   A J    10 年前

    is_writable() 作用 是可写的吗 如果该文件在目录中不存在,将返回false。如果是这种情况,您需要在删除文件名的情况下检查目录本身。如果你这样做, is_writable $file 包含您的文件路径,请执行以下操作:

    $file_directory = dirname($file);
    

    is_writable($file_directory) 以确定文件夹是否可写。

        5
  •  4
  •   Quentin    18 年前

    根据 the documentation for is_writable ,它应该可以工作-但你说的是“文件夹”,所以这可能是 a Windows issue . 评论建议 a workaround .

    (早些时候仓促阅读的文章让我认为后面的斜杠很重要,但这是针对这项工作的)。

        6
  •  3
  •   Studocwho    9 年前

    我写了一个小脚本(我称之为 iswriteable.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>';
        } 
    }
    ?>
    
        7
  •  2
  •   Jason Mock    18 年前

    stat()

    很像一个系统统计,但在PHP中。您要检查的是模式值,就像您在其他语言(即C/C++)中调用stat时所做的一样。

    http://us2.php.net/stat

        8
  •  1
  •   Lasar    18 年前

    根据PHP手册 is_writable 在目录上应该可以很好地工作。

        9
  •  1
  •   Andron    7 年前

    就我而言, 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);
        }
    }
    
        10
  •  0
  •   Nassim    11 年前

    使用创建一个文件 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');