PHP chgrp() Function

What is PHP chgrp() Function?

If you want to change the group of a file to another one, use chgrp() function. You can change the owner of a file if you are a superuser or running with root privilege. Other users may change the group of a file to any group of which that user is a member.

What is group in a file/directory? In Unix based operating system, the file control mechanism determines who can access a file/folder and what they can do with it. There are three type of users of each file/folder – owner (who own it), group (who share the same permission), and other (all the users except owner and group).

Syntax:

chgrp(filename, group)

Parameters:

The Function has 2 required parameters-

filename (Required): It is the path to the file or folder whose group you want to change.

group (Required): It is the new group to which you want to change. It could be a string or a number. When you mention name as a group, then it is a string. On the other hand, when you mention group id, then it is a number.

Return Values:

The function returns-

  • TRUE – if it successfully changes the group.
  • FALSE – if it can’t change the group.

Examples:

Example 1: Changing group using group name-

<?php
chown("docs/dl.pdf", "guest");
?>

Explanation:

The function changes group of the file dl.pdf to “guest”.

Example 2: Changing group using group id-

<?php
chgrp("docs/dl.pdf", 7);
?>

Explanation:

The function changes group of the file dl.pdf to the group whose group id is 7”.

Example 3: Changing group of the file with confirmation-

<?php
if (chgrp("docs/dl.pdf", "group")) {
    echo "File group changed.";
} else {
    echo "File group doesn't change.";
}
?>

Output:

File group changed.

Explanation:

Line 2: The function changes group of the file dl.pdf to “group” and returns TRUE and prints the message on line 3.

Best Practices on chgrp() Function:

  • As the function returns TRUE on success and FALSE on failure, it is good practice to check the function’s success with conditional statement. Check example 3.

Notes on chgrp() Function:

  • On Windows system, this function doesn’t work.
  • This function can’t work on remote files as it can’t access the filesystem.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP chgrp() Function

chgrp() is one of the filesystem functions in PHP which is used to change the group of a file. It helps you to manage your files and directories assigning proper ownership.

Reference:

https://www.php.net/manual/en/function.chgrp.php