PHP Filesystem umask() Function
The PHP Filesystem umask() function is used to change file permissions for files. This function can set PHP's umask to mask & 0777 and return the old umask. However, if we call the umask() function without any arguments, and return the current umask.
When PHP is being used as a server module, the umask is restored when each request is finished.
Syntax
Below is the syntax of the PHP Filesystem umask() function −
int umask ([ int $mask ] )
Parameters
Below is the only required parameter of the umask() function −
| Sr.No | Parameter & Description |
|---|---|
| 1 |
$mask(Required) It is the new umask. |
Return Value
If mask is null, umask() just returns the current umask, otherwise, the old umask is returned.
PHP Version
The umask() function was first introduced as part of core PHP 4 and work well with the PHP 5, PHP 7 and PHP 8.
Example
Here is the basic example to see how the PHP Filesystem umask() function is used to get the current mask value.
<?php // Get the current umask value $current_umask = umask(); // Output the current umask value echo "Current umask value: " . decoct($current_umask) . "\n"; ?>
Output
Here is the outcome of the following code −
Current umask value: 22
Example
This is an additional PHP example code that sets up file permissions using the umask() method, changing and resetting the umask value temporarily.
<?php
$old = umask(0);
chmod("/PhpProjects/sample.txt", 0755);
umask($old);
// Checking
if($old != umask()) {
echo "An error occurred while changing back the umask";
}
?>
Output
This will produce the following output −
#This PHP code generates nothing.
Example
Here is one more example to set a strict umask for file creation using the umask() function.
<?php
// Set a strict umask for file creation
umask(027);
// Create a new file with specific permissions
$file = fopen('/PhpProjects/myfile.txt', 'w');
fclose($file);
// Check the actual permissions set due to umask
$permissions = fileperms('/PhpProjects/myfile.txt');
echo "Actual permissions of '/PhpProjects/myfile.txt': " . decoct($permissions & 0777) . "\n";
?>
Output
This will generate the below output −
Actual permissions of '/PhpProjects/myfile.txt': 644
Example
Here is one more example to use umask() function to umask for secure file creation.
<?php
// Set umask for secure file creation
umask(0177);
// Create a new file with specific permissions
$file = fopen('/PhpProjects/sample.txt', 'w');
fclose($file);
// Check the actual permissions set due to umask
$permissions = fileperms('/PhpProjects/sample.txt');
echo "Actual permissions of 'sample.txt': " . decoct($permissions & 0777) . "\n";
?>
Output
This will lead to the following output −
Actual permissions of 'sample.txt': 755
Summary
The umask() method is a built-in function to change file permissions for files. By changing umask values, you can help ensure security and proper access control in your PHP applications.