W3docs

umask()

In PHP, the umask() function is used to set the default permissions for new files and directories. It is a useful function for working with files and

Introduction

In PHP, the umask() function sets the default permissions for newly created files and directories. It is a useful tool for managing file access in your scripts. In this article, we will cover everything you need to know about umask(), including its syntax, parameters, and practical examples.

Understanding the umask() Function

The umask() function sets a file mode mask that determines the default permissions for newly created files and directories. It accepts an optional parameter representing the new mask. If called without arguments, it returns the current mask without changing it. When a mask is provided, PHP applies it to the system's default permissions (typically 0666 for files and 0777 for directories) using a bitwise AND operation with the inverted mask (default & ~mask). Note that umask() returns the previous mask value and affects the entire PHP process, not just the current script execution.

Syntax of the umask() Function

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

umask($mask);

Here, $mask is the new mask. It must be specified in octal notation (e.g., 022).

Examples of Using umask()

Let's take a look at an example of how the umask() function can be used in PHP.

Example 1: Setting the Default Permissions for New Files

<?php

umask(022);
$file_handle = fopen('example.txt', 'w');
fclose($file_handle);
echo 'File permissions: ' . decoct(fileperms('example.txt') & 0777);
unlink('example.txt');

This example sets the default permissions for new files to 022 using the umask() function, and then creates a new file named example.txt with default permissions of 644. The added fileperms() call verifies the resulting octal permissions. Note that umask() also applies to newly created directories.

Conclusion

The umask() function provides a straightforward way to control default permissions for files and directories in your PHP scripts. We hope that this article has given you a better understanding of how umask() works and how it can be used in your own projects.

Practice

Practice

What does the umask() function in PHP do?