chgrp() 用於變更檔案或目錄的群組擁有權。配合 chown()、chmod() 組成檔案權限管理鐵三角,常用於多用戶協作環境、部署腳本、共享目錄設定。
chgrp(string $filename, string|int $group): bool
| 參數 | 說明 |
|---|---|
$filename |
檔案路徑 |
$group |
群組名稱(字串)或 GID(整數) |
<?php
$file = '/var/www/shared/document.pdf';
$group = 'www-data'; // 或 GID:33
if (chgrp($file, $group)) {
echo "群組變更成功:$group";
} else {
echo "變更失敗";
}
// 驗證
$stat = stat($file);
$groupInfo = posix_getgrgid($stat['gid']);
echo "目前群組:" . $groupInfo['name'] . " (GID: {$stat['gid']})";
?>
<?php
function chgrpRecursive(string $path, string|int $group): array {
$results = ['success' => 0, 'failed' => []];
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
$filePath = $file->getPathname();
if (chgrp($filePath, $group)) {
$results['success']++;
} else {
$results['failed'][] = $filePath;
}
}
return $results;
}
// 使用
$results = chgrpRecursive('/var/www/shared', 'developers');
echo "成功:{$results['success']}, 失敗:" . count($results['failed']);
?>
<?php
function setDeploymentPermissions(string $path, string $user, string $group, int $dirMode = 0755, int $fileMode = 0644): void {
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
$filePath = $file->getPathname();
// 變更擁有者與群組
chown($filePath, $user);
chgrp($filePath, $group);
// 設定權限
$mode = $file->isDir() ? $dirMode : $fileMode;
chmod($filePath, $mode);
}
// 根目錄
chown($path, $user);
chgrp($path, $group);
chmod($path, $dirMode);
}
// 典型 Laravel/專案部署
setDeploymentPermissions(
'/var/www/myapp',
'www-data', // user
'www-data', // group
0755, // 目錄權限
0644 // 檔案權限
);
// storage、bootstrap/cache 需寫入權限
setDeploymentPermissions('/var/www/myapp/storage', 'www-data', 'www-data', 0775, 0664);
setDeploymentPermissions('/var/www/myapp/bootstrap/cache', 'www-data', 'www-data', 0775, 0664);
?>
| 錯誤 | 原因 | 解決 |
|---|---|---|
| Operation not permitted | 非 root、嘗試設定非自身所屬群組 | 以 root 執行、或將用戶加入目標群組 |
| No such file or directory | 路徑錯誤 | 先驗證 file_exists() |
| Invalid argument | 群組名不存在、GID 無效 | 用 getent group groupname 驗證 |
icacls、PowerShell 設定 ACLchown() - 變更擁有者chmod() - 變更權限filegroup() - 取得檔案 GIDfileowner() - 取得檔案 UIDposix_getgrgid() - GID 解析群組資訊posix_getpwuid() - UID 解析用戶資訊setgid 位(chmod g+s):新建檔案自動繼承群組RUN groupadd -g 1000 app && useradd -u 1000 -g app app 固定 UID/GIDchgrp -R group pathchgrp 是多用戶環境下檔案共享的關鍵工具,正確配合 chown、chmod、setgid,能建立安全且便利的協作檔案系統。