【问题标题】:How can I create file with permission then change permission如何创建具有权限的文件然后更改权限
【发布时间】:2013-10-30 23:30:12
【问题描述】:

我认为文件所有者有问题。但是不知道怎么改代码。

我的职能:

public static function createFile($fileName, $mode = 0777 ){
        if (! is_string( $fileName ) || empty( $fileName )) {
            throw new Exception( "File name must be a string and can not be empty", 923050 );
        }

        $touchResult = touch( $fileName );

        if (! $touchResult) {
            throw new Exception( "Error occurs while touch method was executed", 923052 );
        }

        if (! is_int( $mode ) || $mode > 511) {
            throw new Exception( 'invalid mode value', 923051 );
        } else {
            $chmodResult = chmod( $fileName, $mode );

            if (! $chmodResult) {
                throw new Exception("Error occurs while chmod method was executed", 923052);
            }
        }
    }

测试:

public function testCreateFile(){
        $fileToCreate = __DIR__ . "/../../../../../logs/new.txt";

        //Delete file if exist
        if (file_exists( $fileToCreate )) {
            FileHandler::delete( $fileToCreate );
        }

        //Create file. Default mode 0777
        FileHandler::createFile( $fileToCreate );
        $this->assertFileExists( $fileToCreate );

        $filePermisson = substr( sprintf( '%o', fileperms( $fileToCreate ) ), - 4 );
        $this->assertEquals("0777", $filePermisson);

        //Change permission of existing file
        FileHandler::createFile($fileToCreate, 0775);
        $filePermisson = substr( sprintf( '%o', fileperms( $fileToCreate ) ), - 4 );
        $this->assertEquals("0775", $filePermisson);

    }

错误:

有 1 次失败:

1) FileHandlerTest::testCreateFile 断言 '0777' 失败 匹配预期的“0775”。

【问题讨论】:

  • 您错误地使用了octdec() 函数。 octdec( $mode ) > 511 仅在 $mode 是字符串时才有意义 - 但它已经是具有正确权限值的整数。您可以直接比较:$mode > 511(十进制整数)或$mode > 0777(八进制整数)。您可能还应该检查负值。
  • 斯文谢谢我用这种方式更新了代码

标签: php file permissions phpunit file-permissions


【解决方案1】:

fileperms();之前运行clearstatcache();函数以清除缓存

【讨论】:

    猜你喜欢
    • 2021-01-17
    • 2012-04-03
    • 2012-01-29
    • 1970-01-01
    • 2016-02-29
    • 2020-09-29
    • 2011-04-16
    • 2013-06-27
    • 1970-01-01
    相关资源
    最近更新 更多