Skip to content

chgrp()

Introduction

The chgrp() function in PHP changes the group ownership of a file or directory. This article covers its syntax, parameters, return values, and usage examples.

Syntax

The syntax of the chgrp() function is as follows:

The PHP syntax of chgrp() function

php
chgrp($filename, $group)

The $filename parameter specifies the file or directory whose group ownership will be changed. The $group parameter specifies the new group owner of the file or directory.

Parameters

The chgrp() function accepts two parameters: $filename and $group. The $filename parameter is required, and it specifies the file or directory whose group ownership will be changed. The $group parameter is also required, and it specifies the new group owner of the file or directory.

Return Values

The chgrp() function returns a boolean value indicating whether the group ownership was successfully changed or not. The function returns true if the group ownership was changed successfully, and false otherwise.

Examples

Here are a few examples of how the chgrp() function can be used:

The PHP chgrp() function example

php
<?php

// Example 1: Change the group ownership of a file
$filename = "/path/to/file.txt";
$group = "newgroup";
if (chgrp($filename, $group)) {
    echo "Group ownership of file successfully changed.";
} else {
    echo "Failed to change group ownership of file.";
}

// Example 2: Change the group ownership of a directory
$dirname = "/path/to/directory";
$group = "newgroup";
if (chgrp($dirname, $group)) {
    echo "Group ownership of directory successfully changed.";
} else {
    echo "Failed to change group ownership of directory.";
}

Note: chgrp() does not support recursive operations or automatic path expansion (e.g., glob patterns). To change group ownership for all files within a directory, you must iterate through them manually.

Important Notes

  • The executing script must have sufficient privileges (typically root or matching user) to change group ownership.
  • chgrp() does not follow symbolic links; it changes the group of the link itself rather than the target file.

Conclusion

The chgrp() function provides a straightforward way to manage file and directory group ownership in PHP. By understanding its syntax, limitations, and permission requirements, you can safely integrate it into your projects.

Practice

What does the chgrp() function in PHP do?

Dual-run preview — compare with live Symfony routes.