What is the correct way to calculate the new mask when setting permissions for directories in PHP?

When setting permissions for directories in PHP, it is important to calculate the new mask correctly to ensure that the permissions are set as intended. To calculate the new mask, you can use bitwise operators to combine the desired permissions with the current permissions of the directory. This ensures that you are only modifying the permissions that you want to change, while keeping the existing permissions intact.

// Current permissions of the directory
$currentPermissions = fileperms('/path/to/directory');

// Desired permissions (e.g. read, write, execute for owner, group, others)
$desiredPermissions = 0755;

// Calculate the new mask by combining the current permissions with the desired permissions
$newMask = $currentPermissions & 0777 | $desiredPermissions;

// Set the new permissions for the directory
chmod('/path/to/directory', $newMask);