0
我認爲文件所有者存在問題。但我不知道應該如何更改代碼。如何創建具有權限的文件,然後更改權限
我的功能:
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);
}
錯誤:
There was 1 failure:
1) FileHandlerTest::testCreateFile Failed asserting that '0777' matches expected '0775'.
您正在使用'octdec()'功能不正確。 'octdec($ mode)> 511'只有在$ mode是一個字符串時纔有意義 - 但它已經是一個具有正確權限值的整數。您可以直接比較它:'$ mode> 511'(十進制整數)或'$ mode> 0777'(八進制整數)。你也應該檢查一下否定值。 – Sven
斯文謝謝我用這種方式更新了代碼 –